How can I set a timeout for an Async function that doesn't accept a cancellation token?

前端 未结 3 1983
有刺的猬
有刺的猬 2021-01-04 20:13

I have my web requests handled by this code;

Response = await Client.SendAsync(Message, HttpCompletionOption.ResponseHeadersRead, CToken);

3条回答
  •  天命终不由人
    2021-01-04 20:35

    Have a look at How do I cancel non-cancelable async operations?. If you just want the await to finish while the request continues in the background you can use the author's WithCancellation extension method. Here it is reproduced from the article:

    public static async Task WithCancellation( 
        this Task task, CancellationToken cancellationToken) 
    { 
        var tcs = new TaskCompletionSource(); 
        using(cancellationToken.Register( 
                    s => ((TaskCompletionSource)s).TrySetResult(true), tcs)) 
            if (task != await Task.WhenAny(task, tcs.Task)) 
                throw new OperationCanceledException(cancellationToken); 
        return await task; 
    }
    

    It essentially combines the original task with a task that accepts a cancellation token and then awaits both tasks using Task.WhenAny. So when you cancel the CancellationToken the secodn task gets cancelled but the original one keeps going. As long as you don't care about that you can use this method.

    You can use it like this:

    return await Response.Content.ReadAsStringAsync().WithCancellation(token);
    

    Update

    You can also try to dispose of the Response as part of the cancellation.

    token.Register(Reponse.Content.Dispose);
    return await Response.Content.ReadAsStringAsync().WithCancellation(token);
    

    Now as you cancel the token, the Content object will be disposed.

提交回复
热议问题