优势利用Thread.Start VS QueueUserWorkItem的优势、Thread、Start、VS

2023-09-02 21:20:35 作者:送舟行

在多线程.NET编程,什么是决策标准使用ThreadPool.QueueUserWorkItem与通过新的Thread()和Thread.Start()开始自己的线程?

In multithreaded .NET programming, what are the decision criteria for using ThreadPool.QueueUserWorkItem versus starting my own thread via new Thread() and Thread.Start()?

在一个服务器上的应用程序(比方说,一个ASP.NET应用程序或WCF服务),我认为线程池是永远存在的和可用的。怎么样在一个客户端应用程序,就像一个WinForms或WPF应用程序?是否有成本加速旋转的线程池?如果我只是想3或4个线程工作的一些计算在短期内,是能够更好地QUWI或Thread.Start()。

In a server app (let's say, an ASP.NET app or a WCF service) I think the ThreadPool is always there and available. What about in a client app, like a WinForms or WPF app? Is there a cost to spin up the thread pool? If I just want 3 or 4 threads to work for a short period on some computation, is it better to QUWI or to Thread.Start().

推荐答案

线程池是永远存在的,但是,也有分配给基于处理器的数量池中的线程数量有限。对于ASP.NET应用程序,它通常是一个坏主意,使用线程,除非你真的开始关闭一个异步过程,知道不会有大的请求数量(记住,有ThreadPool中的线程数量有限你在你的AppDomain一切运行共享,而且对线程要创建一个使用新的线程(总数现实的限制),以及)。

The ThreadPool is always there, however, there are a finite number of threads allocated to the pool based on the number of processors. For ASP.NET applications, it is generally a bad idea to use Threads unless you really are starting off an Async process and know that there won't be a large number of requests (remember that there are a finite number of threads in the ThreadPool which you share with everything running in your AppDomain and there is a realistic limit on the total number of threads you want to create using new Thread() as well).

有关的WinForms应用程序考虑使用BackgroundWorker而不是使用一个线程或线程池。它使用线程池,但是,它使螺纹上的多线程精明程序员容易之间的通信。

For WinForms apps consider using the BackgroundWorker instead of using a Thread or the ThreadPool. It uses the ThreadPool, however, it makes communicating between threads easier on the multi-thread savvy programmer.

更新

避免使用的的 ThreadPool.QueueUserWorkItem 的作为您的应用程序池可能会消失在任何时间。将这项工作外,或使用WebBackgrounder如果你一定要。

Avoid using ThreadPool.QueueUserWorkItem as your app pool could disappear at any time. Move this work outside or use WebBackgrounder if you must.

从 Hanselman.com - 清单:不要做什么在ASP.NET