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

前端 未结 3 1896
臣服心动
臣服心动 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 11:49

    Your assumption is correct. The statement parameterizedThread.Start(flag) copies the flag variable at the time of the call.

    By contrast, the anonymous delegate captures the original variable in a closure. The variable isn't copied until the delegate executes the DelegateDisplayIt method. At that point, the value may be true or false, depending on where the original thread is in the calling loop.

提交回复
热议问题