我遇到了这个示例,它演示了线程
和循环中的捕获变量
的情况:
代码 1
for (int i = 0; i < 10; i++)
{
new Thread(() => Console.Write(i)).Start();
}
结果 1
0223558779
据说建议的解决方案是创建一个临时变量,如下所示:
代码2
for (int j = 0; j < 10; j++)
{
int temp = j;
new Thread(() => Console.Write(temp)).Start();
}
结果 2
0124356879
看来这个解决方案只是通过使用 temp
变量来消除冗余,该变量将创建 10 个不同的内存位置,但序列仍然没有排序,我明白原因,这与在迭代和启动 future 线程之前,线程执行Console.Write(temp) 的速度不太快,我尝试通过休眠主线程来减慢循环速度,为每个线程提供时间来正确写入,方法是:
代码3
for (int i = 0; i < 10; i++)
{
new Thread(() => Console.Write(i)).Start();
Thread.Sleep(10);
}
它解决了问题,但在实际场景中,我不认为这是一个真正的解决方案,是否有我在这里缺少的技巧或实践来显示完整的正确序列,如 0123456789
?
最佳答案
came across this example that demonstrates the case of Captured Variables within a Thread and a loop
注意 C# 将进行功能更改(在 C#6 IIRC 中):C# 将自动生成要捕获的单独值(因为这是您始终想要的)。
yet the sequence is still not ordered,
当然不是。您无法控制线程的调度顺序。
, is there a trick or a practice I'm missing here to show a complete correct sequence
您需要在线程完成时对结果重新排序,或者 – 如果处理量很小 – 不要使用线程。 (在 Win32 上,创建线程非常昂贵,只有在要执行实质性工作时才使用线程,即使如此,线程池或任务并行库 (TPL) 也是更好的选择。)
关于c# - C# 循环中捕获线程中的变量,解决方案是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26631939/