I have the following code that creates 10 threads which in turn write out messages to the console:
for (int i = 0; i < 10; i++)
{
{
Thread thread = new Thread((threadNumber) =>
{
for (int j = 0; j < 10; j++)
{
Thread.Sleep(200);
Console.WriteLine(string.Format("Thread: {0}, Line: {1}", threadNumber, j));
}
});
thread.Start(i);
}
}
My understanding is that ParameterizedThreadStart
takes an object for which a copy of the reference is sent to the thread. If that is the case since I have not made a local copy of i
within each loop all new threads would point to the same memory location meaning certain thread numbers could be 'missed out'. Having run this though (and even against a larger number of threads/sleep times) each value of i
has its own thread. Can anyone explain why?