Private variables in .net 4.0 tasks

experimenting a bit to find out how everything works. I have the following code ...

for (int i = 0; i < 20; i++) { Task.Factory.StartNew(() => MethodTest(i)); } 

I am wondering why MethodTest almost always gets int 20 (unless I step over in the debugger).

Obviously, something is missing in my understanding, since I assumed that when the “i” is passed, it will be part of the local managed-stream storage.

+7
source share
1 answer

You close the loop variable - try the following:

  for (int i = 0; i < 20; i++) { int x = i; Task.Factory.StartNew(() => MethodTest(x)); } 

It is important to understand that you are creating a closure on variable i , not the current value .

By the time the thread pool starts the first thread (they first get into the queue), the variable i almost certainly be 20, since you left the loop. Now, each running thread will look at the value of the variable i at this point in time.

The fix, as suggested, is to create a new variable inside the loop area and assign this variable the current value i . Since a new variable is used at each iteration of the loop, each created thread now closes its “own" variable, which is isolated and does not change.

The standard reference for explaining what is happening is Closing a loop variable that is considered harmful .

+15
source

All Articles