The foreach identifier and closures

前端 未结 7 1464
误落风尘
误落风尘 2020-11-22 10:51

In the two following snippets, is the first one safe or must you do the second one?

By safe I mean is each thread guaranteed to call the method on the Foo from the s

7条回答
  •  孤城傲影
    2020-11-22 11:13

    In your case, you can avoid the problem without using the copying trick by mapping your ListOfFoo to a sequence of threads:

    var threads = ListOfFoo.Select(foo => new Thread(() => foo.DoSomething()));
    foreach (var t in threads)
    {
        t.Start();
    }
    

提交回复
热议问题