我有這樣的代碼:陣列線程C#
Thread[] threadsArray = new Thread[4];
for (int i = 0; i < 4; i++)
{
threadsArray[i] = new Thread(() => c1.k(i));
}
for (int i = 0; i < 4; i++)
{
threadsArray[i].Start();
}
for (int i = 0; i < 4; i++)
{
threadsArray[i].Join();
}
功能k是這樣的:
void k(int i)
{
while(true)
Console.WriteLine(i);
}
出於某種原因剛剛過去的線程運行並打印4444444 .... 爲什麼並不是所有線程都在運行?
這必須是標準的閉合過度的循環變量是我見過的問題的最古怪的變種。 – 2010-07-19 20:51:36
這一個更類似:http://stackoverflow.com/questions/1930133/c-closures-why-is-the-loopvariable-captured-by-reference – 2010-07-19 21:06:58
相關:「關閉循環變量被認爲是有害的」由Eric Lippert。 http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx – 2010-07-20 07:56:51