问题描述
我前几天读到,对于长时间运行的任务,我最好的办法是手动创建线程,而不是使用 .NET 的线程池或任务并行.当我正在学习 c# 线程时,我真的很想有人启发我,特别是对于长时间运行的 IO 任务.提前致谢.
I read on the other day that for long-running tasks my best bet is to manually create threads instead of using .NET’s thread pool or Task Parallel. I'd really like someone to enlighten me as I am learning about c# threading, specially for long running IO tasks. Thank you in advance.
推荐答案
确实如此.线程池针对小型工作单元进行了优化,您可以通过保留线程池线程来干扰其他工作.
That is true. The thread pool is optimised for small units of work and you can interfere with other work by holding onto a thread pool thread.
我的经验法则是,如果一个操作可能需要超过一秒钟,它不应该在线程池线程上.那可能很长.
My rule of thumb is if an operation can take more than a second, it should not be on a thread pool thread. That is probably quite long.
虽然这是未公开的,但如果您使用 TaskCreationOptions.LongRunning
启动一个 Task
,那么将启动一个新线程来运行该任务.
Although this is undocumented, if you start a Task
with TaskCreationOptions.LongRunning
then a new Thread will be started to run the Task.
对于大多数 IO 任务,您应该真正使用框架方法的异步版本.这些使用内核函数,意味着您不会阻塞任何线程.
For most IO tasks, there are asynchronous versions of the framework methods that you should really use. These make use of kernel functions and mean that you won't be blocking any thread.
一如既往,我建议阅读Joe Albahari 的免费电子书,接着是 Joe Duffy 在 Windows 上的并发编程.后者有 1000 页长,但充满了有用的细节.
As always, I recommend reading Joe Albahari's free ebook,followed by Joe Duffy's Concurrent Programming on Windows. The later is 1000 pages long, but is full of useful details.
这篇关于对于长时间运行的进程,最好手动执行线程而不是线程池,这是真的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!