Thread.Start()与ThreadPool.QueueUserWorkItem() [英] Thread.Start() versus ThreadPool.QueueUserWorkItem()

查看:506
本文介绍了Thread.Start()与ThreadPool.QueueUserWorkItem()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

微软.NET基础类库提供了几种方法来创建一个线程并启动它。基本上调用非常相似每隔一个提供相同服务的种类:创建代表一个执行流程的对象(或以上),它分配一个代表表示执行流程来执行,并最终取决于委托签名,一个目的。作为一个参数

The Microsoft .NET Base Class Library provides several ways to create a thread and start it. Basically the invocation is very similar to every other one providing the same kind of service: create an object representing an execution flow (or more), assign it a delegate representing the execution flow to execute and, eventually, depending on delegate signature, an object as a parameter.

那么,有两种方法(本质):

Well, there are two approaches (essentially):

1)使用 System.Threading.Thread 类。

Thread curr = new Thread(myfunction); /* In a class, myfunction is a void taking an object */
curr.Start(new Object()); /* Or something else to be downcast */



2)使用系统。.Threading.ThreadPool

ThreadPool.QueueUserWorkItem(myfunction, new Object()); /* Same philosophy here */

有什么特别的原因,我应该使用1),2) ??性能方面的原因?模式?什么是最好的办法。

Are there any special reasons why I should use 1) or 2)?? Performance reasons? Patterns? What is the best approach?

我有一种感觉,答案是:经局势依靠。能否请您列举一些情况,一种方法比另一种更好呢?

I have a feeling that the answer is: "Depend by the situation". Could you please list some situations where one approach is better than another?

三江源

推荐答案

开始一个新的线程可以是一个非常昂贵的操作。线程池重用螺纹,从而摊销成本。除非你需要一个专门的线程,线程池是推荐的路要走。通过使用专用线程您对螺纹特定属性如优先级,文化等更多的控制。此外,你不应该做的线程池长时间运行的任务,因为这将迫使池产卵额外的线程。

Starting a new thread can be a very expensive operation. The thread pool reuses threads and thus amortizes the cost. Unless you need a dedicated thread, the thread pool is the recommended way to go. By using a dedicated thread you have more control over thread specific attributes such as priority, culture and so forth. Also, you should not do long running tasks on the thread pool as it will force the pool to spawn additional threads.

在除了选择你提到的.NET 4提供了一些伟大的抽象的并发。退房的任务和平行班以及所有新的PLINQ方法。

In addition to the options you mention .NET 4 offers some great abstractions for concurrency. Check out the Task and Parallel classes as well as all the new PLINQ methods.

这篇关于Thread.Start()与ThreadPool.QueueUserWorkItem()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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