Polly's Policy.TimeoutAsync does not work with PolicyWrap in an async context

后端 未结 1 1659
南方客
南方客 2021-01-21 23:49

This is a FULLY working example (Copy/paste it and play around, just get the Polly Nuget)

I have the following Console app code which makes a POST request to an HTTP cli

相关标签:
1条回答
  • 2021-01-22 00:09

    Polly Timeout policy with the default TimeoutStrategy.Optimistic operates by timing-out CancellationToken, so the delegates you execute must respond to co-operative cancellation. See the Polly Timeout wiki for more detail.

    Changing your execution line to the following should make the timeout work:

    var response = await Policies.PolicyWrap.ExecuteAsync(
        async ct => await _httpClient.PostAsync(/* uri */, new StringContent(request), ct).ConfigureAwait(false), 
        CancellationToken.None // CancellationToken.None here indicates you have no independent cancellation control you wish to add to the cancellation provided by TimeoutPolicy. You can also pass in your own independent CancellationToken.
    );
    

    Polly async executions by default do not continue on captured synchronization context (they execute with .ConfigureAwait(false)), so this can also be shortened to:

    var response = await Policies.PolicyWrap.ExecuteAsync(
        ct => _httpClient.PostAsync(/* uri */, new StringContent(request), ct), 
        CancellationToken.None
    );
    
    0 讨论(0)
提交回复
热议问题