How to pass LongRunning flag specifically to Task.Run()?强调将任务创建标志添加到较新的 API 中可能有点麻烦,尤其是使用 async
图案。
我发现这篇文章声称这不是一个好主意 async
无论如何也不应该使用:http://blog.i3arnon.com/2015/07/02/task-run-long-running/
我的理解是,这个标志在实践中会导致 TPL 启动一个专用线程而不是给线程池带来压力,但特别是如果我的应用程序不涉及大量并行任务,这真的很重要吗?如果我的预期并行度小于默认线程池大小(无论是什么),我是否可以安全地省略该标志 - 最糟糕的情况是线程池可能会在几百毫秒内缺乏线程?
最佳答案
LongRunning
调用 Task.Factory.StartNew
时默认省略标志方法不通过 TaskCreationOptions
参数,因此您可以安全地假设 省略它是安全的 .实际上省略它比包含它更安全,因为这个标志旨在作为一种性能优化技术,而不是作为日常用品。
In general, don't use it unless you find that you really need it. You'd typically only use
LongRunning
if you found through performance testing that not using it was causing long delays in the processing of other work. (citation)
万一
ThreadPool
经常因为它的线程被滥用(在等待 I/O 操作完成时被阻塞)而被饿死,而不是装饰你的所有 Task
s 与 LongRunning
标志,一个更简单、更有效的解决方法可能是增加 ThreadPool
的最小数量。线程与方法 ThreadPool.SetMinThreads
在您的应用程序初始化期间。例如:ThreadPool.SetMinThreads(workerThreads: 100, completionPortThreads: 5);
当您重构应用程序以正确使用异步时,撤消此 hack 会更容易,而不是撤消
LongRunning
在您的代码中随处标记。
关于c# - 在任务上指定 LongRunning 有多重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60146857/