I tend to use the following pattern a lot of different places for a timed delay with countdown notification 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 abstract this pattern into its own system I can use to block any particular thread until a countdown is reached. Is there some sort of best practice for this? It must provide granular status feedback (preferably I could tell it to notify me every second, tenth of a second, etc.), and it must support cancellation (preferably with better response than each second). I feel I should be using the new CountdownEvent
feature in .NET 4.0, or maybe use a Monitor
instead of just sleeping, but I'm hoping for some better insight here.