Simple Threading in C #

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()
    {
        //Create and enqueue threads
        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' .

+5
2

x . x 2 . :

for (int x = 0; x < 2; x++)
{
    int copy = x;
    threadQueue.Enqueue(new Thread(() => WriteNumber(copy)));
}

- . , , WriteNumber, , , - x 2.

, "" copy ... WriteNumber copy - , x .

+18

- , x, 2.

, .

for (int x = 0; x < 2; x++)
{
    int tmp = x;
    threadQueue.Enqueue(new Thread(() => WriteNumber(tmp)));
}
+9

All Articles