Possible duplicate:
C # Captured Variable In Loop
I am working on a few simple streaming applications, but I cannot get this to work:
class ThreadTest
{
static Queue<Thread> threadQueue = new Queue<Thread>();
static void Main()
{
for (int x = 0; x < 2; x++)
{
threadQueue.Enqueue(new Thread(() => WriteNumber(x)));
}
while(threadQueue.Count != 0)
{
Thread temp = threadQueue.Dequeue();
temp.Start();
}
Console.Read();
}
static void WriteNumber(int number)
{
for (int i = 0; i < 1000; i++)
{
Console.Write(number);
}
}
}
The goal is to add streams to the queue in turn, and then alternately go through the queue and pop the stream and execute it. Since I have "x <2" in the for for loop, it should only do two threads: one where it runs WriteNumber (0), and one where it runs WriteNumber (1), which means I should end up get 1000 0 and 1000 1 on my screen in a different order depending on how the threads end up running.
2 000. , , - : - x WriteNumber, , pass-by-value, , , x , , . , , # , 'ref' .