c# - 什么时候不应该在 .Net 中使用 ThreadPool?

标签 c# .net multithreading design-decisions

<分区>

我什么时候应该在 .Net 中使用 ThreadPool?

看起来最好的选择是使用线程池,在这种情况下,为什么它不是唯一的选择?

您对此有何经验?

最佳答案

@Eric,我不得不同意 Dean 的观点。线程很昂贵。您不能假设您的程序是唯一运行的程序。当每个人都贪图资源时,问题就会成倍增加。

I prefer to create my threads manually and control them myself. It keeps the code very easy to understand.

在适当的时候很好。但是,如果您需要一堆工作线程,您所做的只是让您的代码更加复杂。现在您必须编写代码来管理它们。如果您只使用线程池,那么您将免费获得所有线程管理。而且该语言提供的线程池很可能比您自己滚动的任何东西都更健壮、更高效且错误更少。

Thread t = new Thread(new ThreadStart(DoSomething));  
t.Start();  
t.Join();  

我希望您通常在 Start()Join() 之间有一些额外的代码。否则,额外的线程是无用的,您就是在无缘无故地浪费资源。

People are way too afraid of the resources used by threads. I've never seen creating and starting a thread to take more than a millisecond. There is no hard limit on the number of threads you can create. RAM usage is minimal. Once you have a few hundred threads, CPU becomes an issue because of context switches, so at that point you might want to get fancy with your design.

在现代硬件上,一毫秒是很长的时间。在 3GHz 机器上,这是 300 万个周期。再说一次,您不是唯一创建线程的人。您的线程与所有其他程序的线程一起竞争 CPU。如果您使用的线程不是太多,另一个程序也是,那么您使用的线程太多了。

Seriously, don't make life more complex than it needs to be. Don't use the thread pool unless you need something very specific that it offers.

的确如此。不要让生活变得更复杂。如果您的程序需要多个工作线程,请不要重新发明轮子。使用线程池。这就是它在那里的原因。你会推出自己的字符串类吗?

关于c# - 什么时候不应该在 .Net 中使用 ThreadPool?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10274/

相关文章:

c# - 如何从 SQL 中获取项目,使用 linq to sql,其中日期是从今天到提前 30 天,并作为列表返回

c# - System.Random 构造函数中的错误?

.net - 是否可以通过 OData 流式传输实体?

c# - 将 WPF 控件放入 Windows 窗体窗体?

.net - 如何在 WIX 安装项目中添加 ASP.NET web 项目作为引用?

linux - Matlab 2011a 使用 64 位 Linux 上可用的所有内核?

需要 C# 转换帮助

c# - 当前几个 JSON 项具有非十进制值时,将动态 JSON 反序列化为 DataTable 会丢失小数

c - 阻塞套接字

c# - 调用线程无法访问此对象,因为另一个线程拥有它。如何编辑图像?