Differing behavior when starting a thread: ParameterizedThreadStart vs. Anonymous Delegate. Why does it matter?

前端 未结 3 1892
臣服心动
臣服心动 2020-12-19 11:39

When I run the code below the output is \"DelegateDisplayIt\", typically repeated 1-4 times. I\'ve run this code probably 100 times, and not once has the output ever been \"

3条回答
  •  既然无缘
    2020-12-19 12:00

    Let's take the first case:

    for (int i = 0; i < 10; i++)
    {
        bool flag = false;
        new Thread(delegate() { DelegateDisplayIt(flag); }).Start();
        flag = true;
    }
    

    Here when you construct the anonymous delegate the value of flag is false, but when the DelegateDisplayIt method executes, the flag has already been set to true by the next line, and you see the output displayed. Here's another example that illustrates the same concept:

    for (int i = 0; i < 5; i++) 
    {
        ThreadPool.QueueUserWorkItem(state => Console.WriteLine(i));
    }
    

    This will print five times five.

    Now let's take the second case:

    for (int i = 0; i < 10; i++)
    {
        bool flag = false;
        var parameterizedThread = new Thread(ParameterizedDisplayIt);
        parameterizedThread.Start(flag);        
        flag = true;
    }
    

    the value passed to the callback is the one that the variable posses when you call the Start method, which is false and that's why you never see the output in the console.

提交回复
热议问题