开发者

Private variables in .net 4.0 tasks

doing a little experimenting to find out how things work. I have the following code...

 for (int i = 0; i < 20; i++)
 {
      Task.Factory.StartNew开发者_StackOverflow社区(() => MethodTest(i));
 }

I'm wondering why MethodTest receives the int 20 almost always (unless I'm stepping through in debugger).

Obviously there's something missing in my understanding as I assumed that when 'i' is passed it would be part of a managed thread's local storage.


You are closing over the loop variable - try this:

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

The important thing to understand is that you are creating a closure over the variable i, and not its current value.

By the time the thread pool is starting the first thread (they first land in the queue) the variable i will almost certainly be 20 as you have broken out of the loop. Now each thread that is started will look at the value of the variable i at that point in time.

The fix as suggested is to create a new variable inside the scope of the loop and assign the current value of i to that variable. Since a new variable is used on every iteration of the loop each created thread is now closing over its "own" variable, which is isolated and will not change.

The standard reference to explain what is going is "Closing over the loop variable considered harmful".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜