are*_*mes 2 c# multithreading thread-safety
在下面的示例中,似乎ifor循环的索引由每个线程独立修改,导致奇怪的值i(倍数,甚至大于System.Environment.ProcessorCount-1)的值DoWork_Threaded()
如何在C#中正确完成多线程循环?
// Prepare all threads
Thread[] threads = new Thread[System.Environment.ProcessorCount];
// Start all threads
for (int i = 0; i < System.Environment.ProcessorCount; i++)
{
threads[i] = new Thread(() => DoWork_Threaded(i));
threads[i].Start();
}
// Wait for completion of all threads
for (int i = 0; i < System.Environment.ProcessorCount; i++)
{
threads[i].Join();
}
Run Code Online (Sandbox Code Playgroud)
首先,为什么不使用任务并行库而不是滚动自己的线程调度服务?它已经具有确定调度线程的处理器数量的逻辑.
要回答您的实际问题,您将关闭循环变量.看我的文章为什么那是错的:
https://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/
简而言之:i是变量和变量的变化.当lambda执行时,它将使用当前值执行i,而不是在创建委托时使用的值.