Cancel a Thread.Sleep uh Task.Delay the right way

To wait, or not to waitIn one of my Windows Azure Workers I’m using a back-off algorithm to expand the time between checking the queue for new messages. In my solution the time between checks can become as large as 5 minutes. While that helps in making sure I’m not creating unnecessary data transactions and limit the cpu-usage, it won’t help me when I’m deploying a new update. When a new deployment is done the old-running deployment will be gracefully shutdown. Meaning it waits until all processes are done. In the case of a sleep of 5 minutes, it will wait until it’s ready with that sleep instead of cancelling that sleeping. I thought that to be strange, so I was looking into a nice solution.

The solution is easy as long as you have a CancellationToken available to pass to the Task.Delay method. You can create a CancellationToken by using the CancellationTokenSource. I’ve always been using the overload that just takes one argument, but the overload that takes two arguments allows cancellation. The below sample application explains how to use it.

internal class Program
{
    private static void Main(string[] args)
    {
        var tokenSource = new CancellationTokenSource();
        Task consoleReadTask = Task.Run(
            () =>
                {
                    Console.WriteLine("Press the enter key to cancel execution of tasks.");
                    Console.ReadLine();
                    tokenSource.Cancel();
                });

        Task workerTask = Task.Run(
            async () =>
                        {
                            CancellationToken token = tokenSource.Token;
                            try
                            {
                                while (!token.IsCancellationRequested)
                                {
                                    Console.WriteLine("Task output @ {0}", DateTime.Now);
                                    await Task.Delay(60000, token);
                                }
                            }
                            catch (OperationCanceledException)
                            {
                                Console.WriteLine("Cancelled @ {0}", DateTime.Now);
                            }
                        });

        Task.WaitAll(consoleReadTask, workerTask);
        Console.WriteLine("Press the enter key to exit.");
        Console.ReadLine();
    }
}
  • Gravatar puma May 21st, 2013 at 10:09
    Those are way more awesome. Looks for example klipsch is simply made to employ iProducts? I have to have android variations!
  • Gravatar ノーノーヘアー メンズ May 22nd, 2013 at 09:27
    With havin so much content and articles do you ever run into any problems of plagorism or copyright violation? My blog has a lot of unique content I've either created myself or outsourced but it appears a lot of it is popping it up all over the internet without my authorization. Do you know any ways to help prevent content from being ripped off? I'd truly appreciate it.
  • Gravatar 脱毛器 May 22nd, 2013 at 09:27
    Hey there! I know this is kinda off topic however I'd figured I'd ask. Would you be interested in exchanging links or maybe guest authoring a blog article or vice-versa? My site addresses a lot of the same subjects as yours and I feel we could greatly benefit from each other. If you might be interested feel free to shoot me an e-mail. I look forward to hearing from you! Terrific blog by the way!
  • Gravatar ラルフローレン 店舗 May 22nd, 2013 at 21:13
    Thanks for your marvelous posting! I really enjoyed reading it, you are a great author.I will be sure to bookmark your blog and may come back very soon. I want to encourage you to continue your great writing, have a nice evening!
Gravatar