<分区>
我什么时候应该不在 .Net 中使用 ThreadPool?
看起来最好的选择是使用线程池,在这种情况下,为什么它不是唯一的选择?
您对此有何经验?
<分区>
我什么时候应该不在 .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/