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

问题描述

当我运行输出下面的代码是DelegateDisplayIt,通常重复1-4次。我已经运行这段代码大概100次,没有一次曾经被ParameterizedDisplayIt的输出。因此它似乎在其中创建线程,随后的方式开始影响参数是如何传递。当与匿名委托创建新线程的参数是一个参考回原来的变量,但是,当用一个ParameterizedThreadStart委托创建的参数是一个全新的对象?难道我的假设似乎正确吗?如果是这样,这似乎线程构造函数的奇方影响,不是吗?



 静态无效的主要()
{
的for(int i = 0;我小于10;我++)
{
布尔标志= FALSE;

新的Thread(委托(){DelegateDisplayIt(标志);})。开始();

变种parameterizedThread =新主题(ParameterizedDisplayIt);
parameterizedThread.Start(标志);

标志= TRUE;
}

Console.ReadKey();
}

私有静态无效DelegateDisplayIt(对象标志)
{
如果((布尔)标志)
Console.WriteLine(DelegateDisplayIt);
}

私有静态无效ParameterizedDisplayIt(对象标志)
{
如果((布尔)标志)
Console.WriteLine(ParameterizedDisplayIt);
}


解决方案

您的假设是正确的。声明 parameterizedThread.Start(标志)将在调用时标志变量。



相比之下,匿名委托捕获在原始变量。变量是不可复制的,并且在委托执行 DelegateDisplayIt 方法。在这一点上,该值可能是真实的的假,这取决于其中原始线程处于主叫环


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");
}
解决方案

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.

这篇关于ParameterizedThreadStart与匿名委托:启动一个线程时,不同的行为。为什么这有关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 05:33