Why do these two pieces of code return different results(Tasks)

时间:2017-04-24 17:29:01

标签: c# multithreading task

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?

1 个答案:

答案 0 :(得分:0)

因为你的任务从另一个线程开始,当前线程想要等待并增加计数器,因为你创建的委托使用原始计数器,因为计数比创建新任务要快得多。

You can get more help here.