简体   繁体   English

为什么这个锁定语句不起作用?

[英]Why this lock statement doesn't work?

why this lock test doesn't work ? 为什么这个锁定测试不起作用? it's throwing an exception bellow Console.Write that collection was modified.... 它正在抛出一个异常的控制台.Write该集合被修改了....

    static List<string> staticVar = new List<string>();

    static void Main(string[] args)
    {
        Action<IEnumerable<int>> assyncMethod = enumerator =>
                {
                    lock (staticVar)
                        foreach (int item in enumerator)
                            staticVar.Add(item.ToString());


                };

        assyncMethod.BeginInvoke(Enumerable.Range(0, 500000), null, null);
        Thread.Sleep(100);

        Console.Write(staticVar.Count());
        foreach (string item in staticVar)
        {

        }
    }

In order for a lock to be effective it must be used in all cases that a collection is accessed. 为了使锁有效,必须在访问集合的所有情况下使用它。 Be it reading or writing. 无论是阅读还是写作。 So you must add a lock before enumerating the collection 因此,您必须在枚举集合之前添加锁

For example 例如

lock (staticVar) {
    Console.Write(staticVar.Count());
    foreach (string item in staticVar) {

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM