A task that will never end until cancellation is requested

前端 未结 2 550
甜味超标
甜味超标 2020-12-19 02:52

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()         


        
相关标签:
2条回答
  • 2020-12-19 03:19

    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;
    }
    
    0 讨论(0)
  • 2020-12-19 03:32

    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.

    0 讨论(0)
提交回复
热议问题