Cancelling an HttpClient Request - Why is TaskCanceledException.CancellationToken.IsCancellationRequested false?

前端 未结 3 1692
半阙折子戏
半阙折子戏 2020-12-03 00:53

Given the following code:

var cts = new CancellationTokenSource();

try 
{
    // get a \"hot\" task
    var task = new HttpClient().GetAsync(\"http://www.go         


        
3条回答
  •  一生所求
    2020-12-03 01:37

    I set the timeout to infinite to disable it, then I pass in my own cancellation token.

    using(CancellationTokenSource cancelAfterDelay = new CancellationTokenSource(timespan/timeout))
    ...
    catch(OperationCanceledException e)
    {
    if(!cancelAfterDelay.Token.IsCancellationRequested)
    throw new TimeoutException($"An HTTP request to {request.Uri} timed out ({(int)requestTimeout.TotalSeconds} seconds)");
    else
    throw;
    }
    

提交回复
热议问题