Note that there are some explanatory texts on larger screens.

plurals
  1. POSystem.Threading.Timer keep reference to it
    text
    copied!<p>According to [<a href="http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx][1]" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx][1]</a> you need to keep a reference to a System.Threading.Timer to prevent it from being disposed.</p> <p>I've got a method like this:</p> <pre><code>private void Delay(Action action, Int32 ms) { if (ms &lt;= 0) { action(); } System.Threading.Timer timer = new System.Threading.Timer( (o) =&gt; action(), null, ms, System.Threading.Timeout.Infinite); } </code></pre> <p>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.</p> <p>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:</p> <pre><code> class timerstate { internal volatile System.Threading.Timer Timer; }; private void Delay2(Action action, Int32 ms) { if (ms &lt;= 0) { action(); } timerstate state = new timerstate(); lock (state) { state.Timer = new System.Threading.Timer( (o) =&gt; { lock (o) { action(); ((timerstate)o).Timer.Dispose(); } }, state, ms, System.Threading.Timeout.Infinite); } </code></pre> <p>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. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload