C# System.Timers.Timer odd behavior?

≯℡__Kan透↙ 提交于 2019-12-01 11:11:33

Thanks to @TheGeneral for identifying this as the root cause of the OP's issue.

The main issue you are running into here is that your ThreadPool is exhausted (and your Timer is using the ThreadPool), since you have a CPU with only 4 logical cores. This explains why I personally (with 12 cores) am unable to reproduce this.

As per the docs:

By default, the minimum number of threads is set to the number of processors on a system.

So the thread pool scheduler is likely starting with 4 threads. The thread pool scheduler is quite conservative. It doesn't just dish out threads as you ask for them - it sometimes delays creating them to aid in overall system performance (since spinning up threads is expensive).

To fix your immediate issue, you can prompt the thread pool to spin up more threads more quickly, using:

ThreadPool.SetMinThreads(50, 50);

This will ramp it quickly to 50, and then more conservatively after that.

Longer term though, the issue is that you are doing long running operations in the thread pool. This is a bad idea. You may wish to move them to threads, or to long running tasks (which, in practice, are threads). But both of those options have their downside. Fundamentally, you want to keep long running operations outside of the thread pool if possible.

Without understanding why you are using lock it is hard to give great advice. But one option to consider might be to use a BlockingCollection to form a queue - and then have a single separate thread processing that queue. This means your Timer events will just add an entry to the queue and then return - the brunt of the processing will be in the (single) thread that is processing the entries from the queue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!