System.Threading.Timer keep reference to it.
- by Daniel Bryars
According to [http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx][1] you need to keep a reference to a System.Threading.Timer to prevent it from being disposed.
I've got a method like this:
private void Delay(Action action, Int32 ms)
{
if (ms <= 0)
{
action();
}
System.Threading.Timer timer = new System.Threading.Timer(
(o) => action(),
null,
ms,
System.Threading.Timeout.Infinite);
}
Which I don't think keeps a reference to the timer, I've not seen any problems so far, but that's probably because the delay periods used have been pretty small.
Is the code above wrong? And if it is, how to I keep a reference to the Timer? I'm thinking something like this might work:
class timerstate
{
internal volatile System.Threading.Timer Timer;
};
private void Delay2(Action action, Int32 ms)
{
if (ms <= 0)
{
action();
}
timerstate state = new timerstate();
lock (state)
{
state.Timer = new System.Threading.Timer(
(o) =>
{
lock (o)
{
action();
((timerstate)o).Timer.Dispose();
}
},
state,
ms,
System.Threading.Timeout.Infinite);
}
The locking business is so I can get the timer into the timerstate class before the delegate gets invoked. It all looks a little clunky to me. Perhaps I should regard the chance of the timer firing before it's finished constructing and assigned to the property in the timerstace instance as negligible and leave the locking out.