小编Kal*_*Kal的帖子

Polly 的 Policy.TimeoutAsync 不适用于异步上下文中的 PolicyWrap

这是一个完全有效的示例(复制/粘贴它并尝试一下,只需获取 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我已经设置了这样的策略( …

c# asynchronous timeout dotnet-httpclient polly

4
推荐指数
1
解决办法
5217
查看次数

Polly's Fallback 中的动态代表

我在 PolicyRegistry 中有以下策略可以在全局范围内重用:

var fallbackPolicy = Policy
        .Handle<DrmException>().OrInner<DrmException>()
        .Fallback(
            fallbackAction: () => { //should commit or dispose the transaction here using a passed in Func or Action },
            onFallback: (exception) => { Log.Error().Exception(exception).Message($"Exception occurred, message: {exception.Message}.").Write(); }
        );
Run Code Online (Sandbox Code Playgroud)

我有以下代码,我想在fallbackPolicy其中实现:

   if(Settings.DRM_ENABLED)
       drmManager.ExecuteAsync(new DeleteUser(123).Wait();//HTTP Call, throws DrmException if unsuccessful

       //in some cases, there is an if(transaction == null) here (if transaction was passed as a parameter and needs to be committed here)
       transaction.Commit();//if not thrown - commits the transaction
Run Code Online (Sandbox Code Playgroud)

我希望它看起来像这样: …

.net c# fallback transient polly

2
推荐指数
1
解决办法
1761
查看次数