Example of my code:
Timer timer = new Timer(Timer_Tick, null, Timeout.Infinite, Timeout.Infinite);
Mutex timerSync = new Mutex();
void StartWork()
{
timer.Change(0, 1); //Start timer
//Do something...
}
void Dispose()
{
timer.Change(Timeout.Infinite, Timeout.Infinite); //Stop timer
timer.Dispose();
timerSync.Dispose();
//Dispose other things...
}
void Timer_Tick()
{
if (timerSync.WaitOne(0))
{
try
{
//Do something...
}
catch (Exception)
{
//If any exception occurs, abort the "Tick" callback!
return;
}
finally
{
//Whatever happens, release the mutex!
timerSync.ReleaseMutex();
}
}
}
When I stop the timer and dispose it, this not stops the current callback, that generates errors.
In particular, if a callback is in running, I get an ObjectDisposedException related to the mutex.
For the way the execution is structured, if I use that mutex on "Dispose" method, this causes a deadlock.
I have already thought of a solution: Use another try-catch block to handle exceptions related to the mutex.
But I want to know if there is a method to force to cancel any callback of the timer when it is disposed.