Best practice for countdown thread delays

I tend to use the following pattern in different places for a time delay with countdown events and the ability to cancel:

CancellationToken ctoken = new CancellationToken(); for (int i = 0; i < 10; i++) { if (ctoken.IsCancellationRequested) break; Thread.Sleep(1000); if (ctoken.IsCancellationRequested) break; if (Status != null) Status(this, new StatusEventArgs(i)); } 

What I would like to do is an abstract template in my own system, which I can use to block any particular thread until a countdown is reached. Is there any best practice for this? It should provide granular status feedback (preferably, I can say that it notifies me every second, tenth of a second, etc.), and it should support cancellation (preferably with a better answer than every second). I feel like I should use the new CountdownEvent feature in .NET 4.0 or use Monitor instead of just sleeping, but I hope for a better understanding here.

+2
multithreading c # countdownevent
source share
1 answer

The first thing you need to do is separate the feedback and cancellation ideas. That is, you have a feedback mechanism and a cancellation mechanism, but they are completely unrelated. If you can separate these two concepts, then it will become easier for you to cope, and it will also work better.

You want to provide feedback at some interval, which implies a timer. And instead of polling, to see if a cancellation is being requested, you can wait using the wait descriptor.

Something like:

 int i = 0; using (System.Threading.Timer tmr = new System.Threading.Timer((s) => { if (Status != null) Status(this, new StatusEventArgs(i)); ++i; }, null, 1000, 1000)) { token.WaitHandle.WaitOne(TimeSpan.FromSeconds(10))); } 

I assume that you get a CancellationToken from another place (i.e. it passed, or you define it, and others can affect its state).

+2
source share

All Articles