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

前端 未结 3 1700
半阙折子戏
半阙折子戏 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:51

    @Bengie This didn't work for me. I had to alter it a little. IsCancellationRequested always returned true so i couldn't rely on that.

    This worked for me:

    using (CancellationTokenSource cancelAfterDelay = new CancellationTokenSource(TimeSpan.FromSeconds(timeout)))
    {
        DateTime startedTime = DateTime.Now;
    
        try
        {
            response = await request.ExecuteAsync(cancelAfterDelay.Token);
        }
        catch (TaskCanceledException e)
        {
            DateTime cancelledTime = DateTime.Now;
            if (startedTime.AddSeconds(timeout-1) <= cancelledTime)
            {
                throw new TimeoutException($"An HTTP request to {request.Url} timed out ({timeout} seconds)");
            }
            else
                throw;
        }
    }
    return response;
    

提交回复
热议问题