Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Timers.Timer creating active threads

I am using System.Timers.Timer to process job. Sample code as below.

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

after running this job for few hours. I got this error

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

Is this timer thread did not get dispose after use? Do we need to take care of that?

like image 406
Prashant Avatar asked Nov 17 '25 11:11

Prashant


1 Answers

ThreadPool is primarily intended for brief operations i.e. very small task , so if you do use system.Timer then it consume thread of thread pool. So that is causing of problem.

Because if you Work() method, doing too much long operaton like accesing file, web site/webservice or database than this problem will occur.

So solution is to free thread pool thread asap. For this you can do like this:

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);
}
like image 75
Pranay Rana Avatar answered Nov 20 '25 01:11

Pranay Rana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!