【问题标题】:System.Timers.Timer creating active threadsSystem.Timers.Timer 创建活动线程
【发布时间】:2017-12-14 19:06:18
【问题描述】:

我正在使用 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();
 }

在运行此作业几个小时后。 我收到了这个错误

“线程池中没有足够的空闲线程来完成操作。”

这个定时器线程在使用后没有被释放吗?我们需要处理这个吗?

【问题讨论】:

  • 你工作()是否太耗时???..在此之后你没有创建更多线程......
  • yes Work() 正在执行繁重的操作,平均处理时间为 15 分钟。
  • 好的,然后按照我的建议尝试......我为我的 Windows 服务做了同样的事情,它每天都会生成报告......
  • INTERVAL_MIN 的值是多少?我们还需要更好地了解 Work() 的作用。
  • INTERVAL_MIN 设置为 60,工作正在调用 Web 服务并更新本地数据库

标签: c# multithreading timer threadpool


【解决方案1】:

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

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

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

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 2016-11-16
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多