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

Ale*_*dre 4 c# multithreading locking

为什么这个锁定测试不起作用?它正在抛出一个异常的控制台.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)
        {

        }
    }
Run Code Online (Sandbox Code Playgroud)

Jar*_*Par 5

为了使锁有效,必须在访问集合的所有情况下使用它.无论是阅读还是写作.因此,您必须在枚举集合之前添加锁

例如

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

    }
}
Run Code Online (Sandbox Code Playgroud)

  • 锁定的一点是,如果锁定在别处,任何东西都无法进入锁定状态.如果不在它周围,那么锁对一大块代码没有影响.锁必须包含使用synchronized变量的每个代码段. (2认同)