Search code examples
c#multithreadingtimerthreadpool

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?


Solution

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