开发者

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....

    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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜