Use start and stop .Net timer in elapsed time event

i want to do some jobs in the elapsed event of timer that takes time more than the timer interval, as a result when i run my code, since interval of timer is smaller than my job, my timer creates new threads to continue, and when i run my code for a long time period, my memory is corrputed by the lots of threads.

I solved this problem in an interesting way, that is:

startListener()
{
Timer timer = new Timer(100);
timer.elapsed += new Elapsed(elapsed_timer);
timer.start();
}

void elapsed_timer()
{
timer.stop();
try
{
//some work that takes lots of time
}
catch()
{
//some work
}
finally
{
timer.stop();
}
}

my question is:

has this solution any problems for a long time running period applications, or is there any other solutions that is more suitable?

Upvotes: 4

Views: 1636

Answers (1)

hometoast
hometoast

Reputation: 11792

You shouldn't Start and Stop the timer, but rather you could set timer.Enabled = false(msdn doc).

I'd also suggest possibly wrapping your long-running code block in a Monitor.TryEnter block. This would cover the rare (but possible?) chance that there are two elapsed events queued up before the timer.Enabled property is changed.

void elapsed_timer() 
{ 
  timer.Enabled = false; 
  try 
  { 
    //some work that takes lots of time 
  } 
  catch() 
  { 
    //some work 
  } 
  finally 
  { 
    timer.Enabled = true; 
  } 
} 

Upvotes: 3

Related Questions