繁体   English   中英

使用 Polly 从异步函数进行重试

[英]Using Polly for a retry attempt from an async function

我试图重试失败的操作 3 次。

我正在使用 Polly 进行重试操作。

我想在重试操作失败的情况下获得异常并重试 2 次,依此类推。

return await Policy
           .Handle<CustomException>()
           .RetryAsync(3, onRetryAsync: async (exception, retryCount, context) =>
           {
               return await runner.run(params);
           });

函数应该返回

Task<IReadOnlyCollection<string>>

我收到以下错误:

转换为任务返回委托的异步 lambda 表达式无法返回值

我认为在重试策略中运行您的逻辑是不寻常的 - 除非我误解了您的问题。 更常见的是,您通过调用运行逻辑的方法来执行策略。

像这样的东西:

async Task Main()
{
    var polly = Policy
           .Handle<Exception>()        
           .RetryAsync(3, (exception, retryCount, context) => Console.WriteLine($"try: {retryCount}, Exception: {exception.Message}"));

    var result = await polly.ExecuteAsync(async () => await DoSomething());
    Console.WriteLine(result);
}

int count = 0;

public async Task<string> DoSomething()
{
    if (count < 3)
    {
        count++;
        throw new Exception("boom");
    }

    return await Task.FromResult("foo");
}

输出

try: 1, Exception: boom
try: 2, Exception: boom
try: 3, Exception: boom
foo

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM