When I run the code below the output is \"DelegateDisplayIt\", typically repeated 1-4 times. I\'ve run this code probably 100 times, and not once has the output ever been \"
Let's take the first case:
for (int i = 0; i < 10; i++)
{
bool flag = false;
new Thread(delegate() { DelegateDisplayIt(flag); }).Start();
flag = true;
}
Here when you construct the anonymous delegate the value of flag is false, but when the DelegateDisplayIt
method executes, the flag has already been set to true by the next line, and you see the output displayed. Here's another example that illustrates the same concept:
for (int i = 0; i < 5; i++)
{
ThreadPool.QueueUserWorkItem(state => Console.WriteLine(i));
}
This will print five times five.
Now let's take the second case:
for (int i = 0; i < 10; i++)
{
bool flag = false;
var parameterizedThread = new Thread(ParameterizedDisplayIt);
parameterizedThread.Start(flag);
flag = true;
}
the value passed to the callback is the one that the variable posses when you call the Start
method, which is false
and that's why you never see the output in the console.