Alex Rivera | Logout

Correct way to delay the start of a Task

Asked 2011-02-14T09:33:57.493
53

I want to schedule a task to start in x ms and be able to cancel it before it starts (or just at the beginning of the task).

The first attempt would be something like

var _cancelationTokenSource = new CancellationTokenSource();

var token = _cancelationTokenSource.Token;
Task.Factory.StartNew(() =>
    {
        token.ThrowIfCancellationRequested();
        Thread.Sleep(100);
        token.ThrowIfCancellationRequested();
    }).ContinueWith(t =>
    {
        token.ThrowIfCancellationRequested();
        DoWork();
        token.ThrowIfCancellationRequested();
    }, token);

But I feel like there should be a better way, as this would use up a thread while in the sleep, during which it could be canceled.

What are my other options?

Edit
Report

1 Answer

8

The correct answer in the future will probably be Task.Delay. However, that's currently only available through the Async CTP (and in the CTP, it's on TaskEx rather than Task).

Unfortunately, because it's only in CTP, there aren't many good links to documentation for it either.

answered 2011-02-14T09:47:58.800

Your Answer