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.
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?