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 "ParameterizedDisplayIt". So it seems the manner in which the thread is created and subsequently started affects how the parameter is passed. When creating a new thread with an anonymous delegate the parameter is a reference back to the original variable, but when created with a ParameterizedThreadStart delegate the parameter is an entirely new object? Does my assumption seem correct? If so, this seems an odd side affect of the thread constructor, no?
static void Main()
{
for (int i = 0; i < 10; i++)
{
bool flag = false;
new Thread(delegate() { DelegateDisplayIt(flag); }).Start();
var parameterizedThread = new Thread(ParameterizedDisplayIt);
parameterizedThread.Start(flag);
flag = true;
}
Console.ReadKey();
}
private static void DelegateDisplayIt(object flag)
{
if ((bool)flag)
Console.WriteLine("DelegateDisplayIt");
}
private static void ParameterizedDisplayIt(object flag)
{
if ((bool)flag)
Console.WriteLine("ParameterizedDisplayIt");
}