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

问题描述 投票:0回答:1

我正在尝试重试失败的操作 3 次。

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

我想在重试操作失败时获得异常并重试2次等等。

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

函数应该返回

Task<IReadOnlyCollection<string>>

我收到以下错误:

异步 lambda 表达式不能转换为返回委托的任务 返回一个值

c# async-await polly
1个回答
38
投票

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

类似这样的:

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
© www.soinside.com 2019 - 2024. All rights reserved.