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.
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.
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.
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With