线程构造函数中显式委托和方法组之间的区别 [英] Difference between explicit delegate and method group in a thread constructor

查看:92
本文介绍了线程构造函数中显式委托和方法组之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我测试了以下代码行(当然不是同时),据我所知,它们达到了相同的结果。作为一个谨慎的人,我可以想象他们做事的方式之间和方式上会有区别,但是由于缺乏适当的观察样本,我对此一无所知。

I tested the following lines of code (not at the same time, of course) and as far as I can see, they achieve the same result. Being a cautious person, I can imagine that there's a difference between what/how they do stuff but that I'm ignorant of it due to lack of appropriate observation sample.

Thread whee = new Thread((ThreadStart)delegate { someObject.Start(); });
Thread whoo = new Thread(someObject.Start);
Thread whaa = new Thread(() => { someObject.Start(); });

以上之间的区别是什么?

What, if anything, is the difference between the above? Is that information, perhaps, available somewhere in almost plain sight and I'm missing it due to confusion?!

推荐答案

第一个和第三个调用是完全相同的。关于其他两个:

The first and third calls are the exact same thing. Regarding these other two:

//Thread whee = new Thread((ThreadStart)delegate { someObject.Start(); });
//or, using a lambda expression, 
Thread whee = new Thread(() => someObject.Start());

Thread whoo = new Thread(someObject.Start);

在第一个中,您创建一个委托来关闭(或捕获) someObject 变量。当线程调用您的委托时,它将评估变量指向的对象,并在其上调用 Start

In the first one, you create a delegate that closes over (or captures) the someObject variable. When the thread calls your delegate, it will evaluate which object the variable points to, and call Start on it.

在第二个中,急切地评估了 someObject

In the second one, someObject is eagerly evaluated.

Thread whee = new Thread(() => someObject.Start());
Thread whoo = new Thread(someObject.Start);

someObject = someOtherObject;

whee.Start();
whoo.Start();

如果将新对象分配给 someObject 在启动线程之前,您会注意到:

If you assign a new object to your someObject variable before starting the threads, you'll notice that:


  • 第一个线程调用 Start someOtherObject 上,因为关闭变量是延迟计算的。

  • 第二个线程调用 Start 指向原始实例 someObject 所指,因为该变量经过了较早的求值。

  • the first thread calls Start on someOtherObject, because the closure variable was lazily-evaluated.
  • the second thread calls Start on the original instance someObject pointed to, because the variable was eargerly-evaluated.

这篇关于线程构造函数中显式委托和方法组之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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