-1

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?

3
  • 1
    The question is not asked properly but I suspect that you need to assign i into a temporary variable and then use it in SumNumber function otherwise it will use i =2 twice
    – MistyK
    Apr 24, 2017 at 17:31
  • 3
    That's a closure issue. The i passed to both will be the same thus updated to 2. You need to assign it to a local variable first and use that.
    – juharr
    Apr 24, 2017 at 17:33
  • Thank you for the answers, that fixes it but I still don't understand why that happens. Shouldn't i = 0 be passed to the method on the first iteration and i = 1 on the second one?
    – Krasimir
    Apr 24, 2017 at 17:40

1 Answer 1

0

Because your task starts in another thread and current thread want wait for that and increment the counter, since the delegate you have created uses the original counter, because counting is done much faster than creating a new task.

You can get more help here.

Not the answer you're looking for? Browse other questions tagged or ask your own question.