Frage

I need a task that never ends until cancellation is requested. At the moment the simplest way to do that is:

var cancellation = new CancellationTokenSource();

var task = Task.Factory.StartNew(async () =>
{
    while (true)
    {
        await Task.Delay(10000, cancellation.Token);
    }
}, cancellation.Token).Unwrap();

What I don't like is a call to Task.Delay method because it requires limited time interval for waiting.

Is there more elegant solution?

War es hilfreich?

Lösung

As an alternative to TaskCompletionSource with token.Register, here are some one-liners:

var task = new Task(() => {}, token); // don't do task.Run()!

Or, simply this:

var task = Task.Delay(Timeout.Infinite, token);

There's even a nice optimization for Timeout.Infinite in the current Task.Delay implementation.

Andere Tipps

You should be able to subscribe to the cancellation of the token and complete the task then:

public static Task UntilCancelled(CancellationToken tok)
{
    var tcs = new TaskCompletionSource<object>();
    IDisposable subscription = null;
    subscription = tok.Register(() =>
    {
        tcs.SetResult(null);
        subscription.Dispose();
    });

    return tcs.Task;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top