Multithread C# : Does not return the result as I expected

I am new and I have a multi-threaded implementation in c #. But the result returns an error. File <number.txt> have number 0 to 1000. But the return value is 1 to 1000. Not 0. Please help me understand the problem. Thank you.

static void Number(int number)
{
    List<string> l_number = new List<string>(File.ReadAllLines("number.txt"));
    Console.WriteLine(l_number[number]);
}

static void Main(string[] args)
{
    List<Thread> l_thread = new List<Thread>();
    int soThread = 10;

    Thread thread1 = new Thread(delegate ()
    {
        var numnum = 0;
        while (true)
        {
            for (int i = 0; i < soThread; i++)
            {
                Thread threadnew = new Thread(delegate ()
                {
                    //Console.WriteLine(numnum);
                    Number(numnum);
                });
                threadnew.Start();
                l_thread.Add(threadnew);
                numnum++;
                Thread.Sleep(100);
            }
            foreach (Thread item in l_thread)
            {
                item.Join();
            }
        }
    });

Upvotes: 2

Views: 113

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062502

You are capturing numnum - it isn't per-thread, and the timing means it isn't the value at the time it is captured - it is the value at the time the thread gets scheduled; try instead creating a copy of the variable per scope, i.e.

for (int i = 0; i < soThread; i++)
{
    int copy = numnum;
    Thread threadnew = new Thread(delegate ()
    {
        //Console.WriteLine(copy);
        Number(copy);
    });

    // ...
}

Upvotes: 5

Related Questions