2

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);
}
remdao
  • 885
  • 3
  • 17
  • 23

2 Answers2

6

It's "thread-safe" in the sense that the call to Change won't actually corrupt the timer.

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

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • Thanks, yes maybe I'll do a Sleep before DoStuff() to give timerCallback2 time to finish, or I'll just add a lock. – remdao Jun 17 '10 at 08:35
2

Per MSDN documentation the Timer type is thread safe, so the only place you have to be careful is where you call DoStuff();.

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
  • I read "Any instance members are _not_ thread-safe". http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx – H H Jun 16 '10 at 14:26
  • 1
    @Henk: Thats in the System.Timers class, not the Threading.Timer Class, which is thread safe – Tony The Lion Jun 16 '10 at 14:37