I have been playing around with Threads and Tasks (.net 4) and noticed some odd behavior when you launch multiple threads without waiting a few miliseconds between each thread started call.
The example below when run does not output what I expected:
1
2
1
2
But instead only outputs:
2
2
2
2
Below is the code that I am running.
public static void Main()
{
var items = new[] {"1", "2"};
foreach (var item in items)
{
var thread = new Thread(() => Print(item));
thread.Start();
//var task = Task.Factory.StartNew(() => Print(item));
}
}
static void Print(string something)
{
while (true)
{
Console.WriteLine(something);
Thread.Sleep(1000);
}
}
Now when I call Thread.Sleep(50) after the thread.Start() then only does the output look as expected
1
2
1
2
My question is:
- Why when you do not wait between launching both threads does the first
thread loose the method’s parameter value you initially started it with?
i.e. first thread is launched with parameter of “1”, second thread is launched with parameter of “2”, however first thread’s parameter becomes “2” as well? This makes no sense, especially since Print() method paramter is a value type of string.
Google “access to modified closure”. What’s happening is your local variable “item” is getting it’s value changed before the Print function is invoked. A solution would be to create a new variable inside the scope of the loop and assign item to it.