ThreadPool.RegisterWaitForSingleObject with CancellationTokenSource

Some days ago I was inspired by the blog entry Periodic Execution in .NET. I found it great to have a mechanism to periodically do some work but have also the possibility to do some work when my method gets alerted.

I was thinking of a mechanism where a method (like DoSomeWork) get’s called after a period of time. But I don’t want it call after each x seconds. I want to call it once, do the work and when all lights are green I want to schedule the method call again. So in general any sort of timer would not be the best option. I would give the ThreadPool.RegisterWaitForSingleObject a try. In my scenario I’ve multiple worker. So each worker registers it own DoSomeWork method. But I would also shutdown all workers graecefully from an external method. I decided to use a CancellationTokenSource for shutdown all workers with one signal. I use the CancellationTokenSource.Token.WaitHandle as the waitobject for the ThreadPool.RegisterWaitForSingleObject call. And now when the external method decided to shutdown all workers it must only call the Cancel method on the CancellationTokenSource to signal all workers that they should finish there work and should not schedule another call to there DoSomeWork method.