I was trying out using Tasks for multithreading and here is the oddity I came across:
tasks[0] = Task.Run(() => SumNumbers(0, end));
tasks[1] = Task.Run(() => SumNumbers(1, end));
for (int i = 0; i <= 1; i++)
{
tasks[i] = Task.Run(() => SumNumbers(i, end));
}
The first two lines return correct results, whereas the solution with cycles doesn't. Is there an explanation to this?
答案 0 :(得分:0)
因为你的任务从另一个线程开始,当前线程想要等待并增加计数器,因为你创建的委托使用原始计数器,因为计数比创建新任务要快得多。