开发者

Why this lock statement doesn't work?

开发者 https://www.devze.com 2022-12-30 20:42 出处:网络
why this lock test doesn\'t work ? it\'s throwing an exception bellow Console.Write that collection was modified....

why this lock test doesn't work ? it's throwing an exception bellow Console.Write that collection was modified....

    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) {

    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消