3

I have a timer that it's callback do somethings:

The timer:

dataProcessingTimer = new System.Threading.Timer(new TimerCallback(DataProcessingTimerHandler), null, 0, _dataProcessingTimerPollingInterval);

The callback:

void DataProcessingTimerHandler(object param)
{
    // some code.. (sometimes the stop function called from here).
}

When I want to stop the timer I called my stop function :

public void Stop()
{

    if (_dataProcessingTimer != null)
    {
         ManualResetEvent timerDisposeHandler = new ManualResetEvent(false);
         _dataProcessingTimer.Dispose(timerDisposeHandler);
         _dataProcessingTimer = null;

         timerDisposeHandler.WaitOne();
    }

}

The timerDisposeHandler.WaitOne(); use for sure the dispose is done befoer the code that follows the stop function.

But sometimes when the stop function is call in the middel of callback the waitone stuck all.

It's seem that the WaitOne stuck the callback but I don't understand why it's happening, is the timer callback is not found in its own thread? why the thread of the stop function should stuck it?

I would love if someone could explain to me the situation and give me a solution.

Hodaya Shalom
  • 4,327
  • 12
  • 57
  • 111

1 Answers1

2

You are deadlocking your timer callback. From MSDN: "The timer is not disposed until all currently queued callbacks have completed."

In other words, the System.Threading.Timer class will not dispose itself until your callback has completed. But your callback refuses to complete until the Stop() method returns. And the Stop() method refuses to return until the dispose has completed.

If you really must wait to be notified of the completion of the dispose, you have two options: delay the call to Stop() until after the callback has completed; or delay the wait until after the callback has completed. What you can't do is try to wait inside the same method that is blocking the event you're waiting for.

IMHO the best solution is to just not wait for the Dispose() to complete. What is the point of doing that? Do you really need to wait? If so, why?

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
  • I really need to wait because the code that came after the stop need to use data that I recive on the callbackes, So I must wait it is end. – Hodaya Shalom Oct 20 '14 at 08:32
  • 3
    If you have code that needs the data you receive on the callbacks, then you _definitely_ don't want to call Stop() from a callback, because that's just another layer of deadlock waiting to happen. I think it's questionable to have the callback signaling the stop at all, but assuming you really really need that, then you need to set things up so that the callback simply signals some code that will execute later/elsewhere to actually perform the stop and then process all of the data the callbacks have gathered for you. – Peter Duniho Oct 20 '14 at 08:39