【发布时间】:2018-07-30 01:58:13
【问题描述】:
我的代码示例:
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();
}
}
}
当我停止计时器并处理它时,这不会停止当前的回调,这会产生错误。
特别是,如果回调正在运行,我会收到与互斥锁相关的 ObjectDisposedException。
对于执行的结构化方式,如果我在“Dispose”方法上使用该互斥锁,则会导致死锁。
我已经想到了一个解决方案:使用另一个 try-catch 块来处理与互斥锁相关的异常。
但我想知道是否有一种方法可以强制取消定时器的任何回调。
【问题讨论】:
标签: c# multithreading timer mutex