I have a Windows Service implemented in C# that needs to do some work every so often. I\'ve implemented this using a System.Threading.Timer
with a callback method t
With this code
timer = new Timer( state => {
// simulate some work that takes ten seconds
Thread.Sleep( tickInterval * 10 );
// when the work is done, schedule the next callback in one second
timer.Change( tickInterval, Timeout.Infinite );
},
null,
tickInterval, // first callback in one second
Timeout.Infinite );
it is almost certain that you will Dispose the timer while it is sleeping.
You will have to safeguard the code after Sleep() to detect a Disposed timer. Since there is no IsDisposed property a quick and dirty static bool stopping = false;
might do the trick.