启动线程时的不同行为:ParameterizedThreadStart vs. Anonymous Delegate。为什么这有关系? [英] Differing behavior when starting a thread: ParameterizedThreadStart vs. Anonymous Delegate. Why does it matter?

查看:232
本文介绍了启动线程时的不同行为:ParameterizedThreadStart vs. Anonymous Delegate。为什么这有关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行下面的代码输出是DelegateDisplayIt,通常重复1-4次。我运行这个代码可能100次,而不是一次有输出曾经参数化的显示。因此,似乎线程被创建和随后开始的方式影响如何传递参数。当使用匿名委托创建一个新线程时,参数是一个返回原始变量的引用,但是当使用ParameterizedThreadStart委托创建时,该参数是一个全新的对象?我的假设似乎是正确的吗?如果是这样,这似乎是线程构造函数的奇怪的副作用,不是吗?

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 "ParameterizedDisplayIt". So it seems the manner in which the thread is created and subsequently started affects how the parameter is passed. When creating a new thread with an anonymous delegate the parameter is a reference back to the original variable, but when created with a ParameterizedThreadStart delegate the parameter is an entirely new object? Does my assumption seem correct? If so, this seems an odd side affect of the thread constructor, no?

static void Main()
{
    for (int i = 0; i < 10; i++)
    {
        bool flag = false;

        new Thread(delegate() { DelegateDisplayIt(flag); }).Start();

        var parameterizedThread = new Thread(ParameterizedDisplayIt);
        parameterizedThread.Start(flag);

        flag = true;
    }

    Console.ReadKey();
}

private static void DelegateDisplayIt(object flag)
{
    if ((bool)flag)
        Console.WriteLine("DelegateDisplayIt");
}

private static void ParameterizedDisplayIt(object flag)
{
    if ((bool)flag)
        Console.WriteLine("ParameterizedDisplayIt");
}


推荐答案

parameterizedThread.Start(flag)语句在调用时复制标志变量。

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

匿名代理捕获关闭中的原始变量。在委托执行 DelegateDisplayIt 方法之前,不会复制该变量。此时,值可能为true false,具体取决于原始线程在调用循环中的位置。

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.

这篇关于启动线程时的不同行为:ParameterizedThreadStart vs. Anonymous Delegate。为什么这有关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆