cancellationtoken timeout vs task.delay() and timeout

前端 未结 1 1553
深忆病人
深忆病人 2020-12-13 15:43

I want to run an operation that should timeout after n milliseconds. I\'ve implemented it two ways, one by cancelling the operation myself after waiting n milliseconds, and

1条回答
  •  借酒劲吻你
    2020-12-13 16:38

    I'm not sure that your worry is justified, but I'm going to assume that it is.

    The problem with your code that uses Task.Delay() is that you're not actually canceling the operation. This might mean that you're wasting resources or misinforming your users (you tell them that the operation timed out, while the operation is still running and will most likely complete successfully).

    Now, if you want to make sure that the cancellation token starts ticking only after the operation is started, then do that:

    var source = new CancellationTokenSource();
    var task = SomeOperationAsync(source.Token);
    source.CancelAfter(TimeSpan.FromMilliseconds(n));
    await task;
    

    If you do this often, you might want to encapsulate this logic into a method (might need a better name):

    public static async Task WithTimeoutAfterStart(
        Func operation, TimeSpan timeout)
    {
        var source = new CancellationTokenSource();
        var task = operation(source.Token);
        source.CancelAfter(timeout);
        await task;
    }
    

    Usage:

    await WithTimeoutAfterStart(
        ct => SomeOperationAsync(ct), TimeSpan.FromMilliseconds(n));
    

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