System.Timers.Timer 创建活动线程

System.Timers.Timer creating active threads

我正在使用 System.Timers.Timer 处理作业。 示例代码如下。

 private static Timer timer = null;
  timer = new Timer(INTERVAL_MIN * 1000 * 60);
  timer.Elapsed += timer_Elapsed;
  timer.start();

 private static void timer_Elapsed(object sender, ElapsedEventArgs e)
 {
     Work();
 }

在 运行 完成这项工作几个小时后。 我收到这个错误

“There were not enough free threads in the ThreadPool to complete the operation.”

这个计时器线程在使用后没有得到处理吗?我们需要处理这个问题吗?

ThreadPool 主要用于简短的操作,即非常小的任务,所以如果你确实使用 system.Timer 那么它会消耗线程池的线程。这就是问题所在。

因为如果你Work()方法,做太多长的操作,比如访问文件,网络site/webservice或数据库,就会出现这个问题。

所以解决方案是尽快释放线程池线程。为此,您可以这样做:

private static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    //by doing below it will release thread pool thread and cosume thread where long running option can be performed 
    new Thread (Work).Start();
    //or try with TPL like this 
    Task.Factory.StartNew(() => 
    {
       Work();
    }, TaskCreationOptions.LongRunning);
}