3

这是一个完整的工作示例(复制/粘贴它并玩弄,只需获取 Polly Nuget)

我有以下控制台应用程序代码,它向“ http://ptsv2.com/t/v98pb-1521637251/post ”上的 HTTP 客户端沙箱发出 POST 请求(您可以访问此链接“ http://ptsv2.com/ t/v98pb-1521637251 ”查看配置或让自己成为“厕所”):

class Program
{
    private static readonly HttpClient _httpClient = new HttpClient()
        ; //WHY? BECAUSE - https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
    static void Main(string[] args)
    {
        _httpClient.BaseAddress = new Uri(@"http://ptsv2.com/t/v98pb-1521637251/post");
        _httpClient.DefaultRequestHeaders.Accept.Clear();
        _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));

        var result = ExecuteAsync("Test").Result;
        Console.WriteLine(result);
        Console.ReadLine();
    }

    private static async Task<string> ExecuteAsync(string request)
    {
        var response = await Policies.PolicyWrap.ExecuteAsync(async () => await _httpClient.PostAsync("", new StringContent(request)).ConfigureAwait(false));
        if (!response.IsSuccessStatusCode)
            return "Unsuccessful";
        return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
    }
}

Http 客户端等待 4 秒,然后返回响应。

我已经设置了这样的策略(超时策略设置为等待 1 秒的响应):

public static class Policies
{
    public static TimeoutPolicy<HttpResponseMessage> TimeoutPolicy
    {
        get
        {
            return Policy.TimeoutAsync<HttpResponseMessage>(1, onTimeoutAsync: (context, timeSpan, task) =>
            {
                Console.WriteLine("Timeout delegate fired after " + timeSpan.TotalMilliseconds);
                return Task.CompletedTask;
            });
        }
    }
    public static RetryPolicy<HttpResponseMessage> RetryPolicy
    {
        get
        {
            return Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
                    .Or<TimeoutRejectedException>()
                    .RetryAsync(3, onRetryAsync: (delegateResult, i) =>
                    {
                        Console.WriteLine("Retry delegate fired for time No. " + i);
                        return Task.CompletedTask;
                    });
        }
    }
    public static FallbackPolicy<HttpResponseMessage> FallbackPolicy
    {
        get
        {
            return Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
                    .Or<TimeoutRejectedException>()
                    .FallbackAsync(new HttpResponseMessage(HttpStatusCode.InternalServerError), onFallbackAsync: (delegateResult, context) =>
                    {
                        Console.WriteLine("Fallback delegate fired");
                        return Task.CompletedTask;
                    });
        }
    }

    public static PolicyWrap<HttpResponseMessage> PolicyWrap
    {
        get
        {
            return Policy.WrapAsync(FallbackPolicy, RetryPolicy, TimeoutPolicy);
        }
    }
}

但是,onTimeoutAsync 委托根本没有被命中,控制台打印出以下内容:

Retry delegate fired for time No. 1 //Hit after 4 seconds
Retry delegate fired for time No. 2 //Hit after 4 more seconds
Retry delegate fired for time No. 3 //Hit after 4 more seconds
Fallback delegate fired
Unsuccessful

它包含在 PolicyWrap 中并且是异步的,我不知道为什么它没有被击中。任何信息都非常感谢。

4

1 回答 1

4

Polly Timeout 策略默认TimeoutStrategy.Optimistic通过超时操作CancellationToken,因此您执行的代表必须响应合作取消。有关更多详细信息,请参阅Polly Timeout wiki

将执行行更改为以下内容应该可以使超时起作用:

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 异步执行不会在捕获的同步上下文上继续(它们使用 执行.ConfigureAwait(false)),因此也可以将其缩短为:

var response = await Policies.PolicyWrap.ExecuteAsync(
    ct => _httpClient.PostAsync(/* uri */, new StringContent(request), ct), 
    CancellationToken.None
);
于 2018-03-21T19:31:03.707 回答