次の 2 つのスニペットで、最初のスニペットは安全ですか、それとも 2 番目のスニペットを実行する必要がありますか?
安全とは、各スレッドが、スレッドが作成されたのと同じループ反復から Foo のメソッドを呼び出すことが保証されていることを意味しますか?
それとも、新しい変数「ローカル」への参照をループの各反復にコピーする必要がありますか?
var threads = new List<Thread>();
foreach (Foo f in ListOfFoo)
{
Thread thread = new Thread(() => f.DoSomething());
threads.Add(thread);
thread.Start();
}
-
var threads = new List<Thread>();
foreach (Foo f in ListOfFoo)
{
Foo f2 = f;
Thread thread = new Thread(() => f2.DoSomething());
threads.Add(thread);
thread.Start();
}
更新: Jon Skeet の回答で指摘されているように、これは特にスレッド化とは関係ありません。