Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private variables in .net 4.0 tasks

Tags:

c#

.net

task

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(() => 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.

like image 788
RekrowYnapmoc Avatar asked Jul 14 '11 01:07

RekrowYnapmoc


People also ask

What do private variables do in C#?

Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.

Can we access private variable through object?

We cannot access a private variable of a class from an object, which is created outside the class, but it is possible to access when the same object is created inside the class, itself.

What are the differences between .NET task and .NET thread?

Differences Between Task And ThreadThe Thread class is used for creating and manipulating a thread in Windows. A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel. The task can return a result.


1 Answers

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".

like image 162
BrokenGlass Avatar answered Oct 09 '22 04:10

BrokenGlass