Distinguish timeout from user cancellation

后端 未结 2 2024
执念已碎
执念已碎 2020-12-05 07:21

HttpClient has a builtin timeout feature (despite being all asynchronous, i.e. timeouts could be considered orthogonal to the http request functionality and thu

相关标签:
2条回答
  • 2020-12-05 07:53

    The accepted answer is certainly how this should work in theory, but unfortunately in practice IsCancellationRequested does not (reliably) get set on the token that is attached to the exception:

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

    0 讨论(0)
  • 2020-12-05 07:54

    Yes, they both return the same exception (possibly because of timeout internally using a token too) but it can be easily figured out by doing this:

       catch (OperationCanceledException ex)
                {
                    if (token.IsCancellationRequested)
                    {
                        return -1;
                    }
    
                    return -2;
                }
    

    so basically if you hit the exception but your token is not cancelled, well it was a regular http timeout

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