Lambda expressions with multithreading in C#

后端 未结 3 1461
心在旅途
心在旅途 2020-12-19 15:19

I am trying to understand why this program doesn\'t work

Expected output: numbers 0-19 in random order What I get when I run: some numbers repeat, sometimes 20 is pr

相关标签:
3条回答
  • 2020-12-19 15:38

    As Jakub already told you, you need to copy i into another local variable local. In your code, the Delegates have direct access to i itself, not a copy of i, so they print out the very current value of i, which may be greater than when you started the thread. This is called closure.

    0 讨论(0)
  • 2020-12-19 15:41
    public void processinThreads()
    {
        for (int i = 0; i < 20; i++)
        {
            int local = i;
            Thread t = new Thread(new ThreadStart(()=>DoSomething(local, processCallback)));
            t.Start();
        }
    }
    

    Your problem is related to closure over lambda.

    0 讨论(0)
  • 2020-12-19 15:41

    You should just use the TPL, its a lot easier and recommended over manual thread management:

    Parallel.For(0, 20, x => {
        Thread.Sleep(1000);
        Console.WriteLine("IN callback: The value I got is " + x);
    });
    

    This will also block until the loop finishes, if you don't want that you can use the TPL Task, but I would definitely recommend avoiding threads.

    0 讨论(0)
提交回复
热议问题