- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我曾帮助一位客户开发过一段时间后停止工作的应用程序(它最终又开始工作了)。
问题是当 Task
失败时它使用了 Thread.Sleep
5 秒(在任务中)。由于每两秒可能有多达 800 个任务排队,您可以想象如果其中许多任务失败并调用 Thread.Sleep
会出现什么问题。这些作业均未标记有 TaskCreationOptions.LongRunning
。
我重写了任务,这样 Thread.Sleep
(或 Task.Delay
就此而言)就不再那么重要了。
但是,我对 TaskScheduler
(默认设置)在那个场景中做了什么很感兴趣。如何以及何时增加线程数?
最佳答案
根据 MSDN
Behind the scenes, tasks are queued to the ThreadPool, which has been enhanced with algorithms (like hill-climbing) that determine and adjust to the number of threads that maximizes throughput.
ThreadPool将具有最大线程数,具体取决于环境。随着您创建更多的 Task
,池可以并发运行它们,直到达到其最大线程数,此时任何进一步的任务都将排队。
如果您想找出ThreadPool
线程的最大数量,您可以使用System.Threading.ThreadPool.GetMaxThreads
(您需要传入两个 out int 参数,一个将填充最大工作线程数,另一个将填充最大异步 I/O 线程数)。
如果您想更好地了解您的应用程序在运行时发生了什么,您可以使用 Visual Studio's threads window通过转到“调试”->“Windows”->“线程”(只有在调试时才会出现该条目,因此您需要先在应用程序中设置断点)。
This post可能感兴趣。看起来 default task scheduler除非您使用 TaskCreationOptions.LongRunning
,否则只需将任务排队到 ThreadPool 的队列中。这意味着由 ThreadPool
决定何时创建新线程。
关于c# - TPL 如何确定要使用的线程数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17483135/
我是一名优秀的程序员,十分优秀!