I want something very simple
// increment counter
Interlocked.Increment(ref _counter);
// automatically decrement counter after 1 sec
Timer timer = new Timer((o) => {
Interlocked.Decrement(ref _counter);
(o as Timer).Dispose();
}, timer, 1000, Timeout.Infinite);
this code, however, is not compile-able
Use of unassigned local variable 'timer'
Any easy way to fix that? It must be Threading.Timer
.
P.S.: I am not sure if I must call Dispose
, it's obviously un-managed resource and it's IDisposable
, still on msdn they warn
As long as you are using a Timer, you must keep a reference to it. As with any managed object, a Timer is subject to garbage collection when there are no references to it. The fact that a Timer is still active does not prevent it from being collected.
And I actually want it to be be collected (auto-disposed?). So, to dispose or to not dispose?