2

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();
            }
        }
    });
Fred
  • 3,365
  • 4
  • 36
  • 57
  • You may found [this link](https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-parallel-library-tpl) usefull – vasily.sib Apr 23 '19 at 11:14
  • Possible duplicate of [Captured variable in a loop in C#](https://stackoverflow.com/questions/271440/captured-variable-in-a-loop-in-c-sharp) – canton7 Apr 23 '19 at 11:20

1 Answers1

5

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);
    });

    // ...
}

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900