这是真的,对于长时间运行的过程中,最好是做线程池的线程手动呢?线程、这是、长时间、过程中

2023-09-04 00:39:58 作者:我是魔鬼

我读了一天,对于长时间运行的任务我最好的选择是手动创建使用.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 那么新的线程将启动运行任务。

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.

和往常一样,我建议你阅读乔阿尔巴哈利的免费电子书, 其次乔·达菲的在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.