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

老子叫甜甜 提交于 2019-12-02 01:04:47

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
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!