本文介绍了计时器(系统线程)线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人知道此代码是否是线程安全的,还是在调用timer2.Change时必须使用锁?
Does anyone know if this code would be thread safe, or do I have to use lock when calling timer2.Change?
Timer timer1 = new Timer(timerCallback1);
Timer timer2 = new Timer(timerCallback2);
timer1.Change(5000, 5000);
timer2.Change(3000, 3000);
public void timerCallback1(object state)
{
timer1.Change(Timeout.Infinite, Timeout.Infinite);
timer2.Change(Timeout.Infinite, Timeout.Infinite);
DoStuff();
timer1.Change(5000, 5000);
timer2.Change(3000, 3000);
}
推荐答案
从某种意义上说,对Change
的调用实际上不会破坏计时器,这是线程安全的".
It's "thread-safe" in the sense that the call to Change
won't actually corrupt the timer.
但是,从某种意义上来说,这绝对不是一种线程安全的"竞争条件(当您进入DoStuff
时,无法确保timerCallback2
不在运行).
However, it's not "thread-safe" in the sense that you definitely have a race condition (it's not possible to ensure that timerCallback2
isn't running when you're in DoStuff
).
这篇关于计时器(系统线程)线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!