具有功能的 Polly 重试策略不等待结果

我正在尝试将我现有的函数转换为 Polly Retry 策略


public static T Execute<T>(Func<T> getTask) where T : Task

{

    var retryCount = 3;

    while (retryCount-- > 0)

    {

        try

        {

            getTask().Wait();

            return getTask();

        } catch(Exception ex){

            // handle retry

        }

    }

}

转换成这个


public static T Execute<T>(Func<T> func) where T : Task

{

    var task = func();

    Policy.Handle<HttpRequestException>()

        .Or<TimeoutException>()

        .WaitAndRetryAsync(

            3,

            retryAttempt => TimeSpan.FromSeconds(Math.Pow(5, retryAttempt)),

            (exception, timeSpan, retryCount, context) =>

            {

                //do some logging

            })

        .ExecuteAsync(func).Wait();

    return task;

}

和测试代码是


var retryCount = 0;

var res = HttpRetryWrapper.Execute(() => Task.Factory.StartNew<string>(function: () =>

{

    if (++retryCount == 3)

    {

        return "fake";

    }

    throw new TimeoutException();

}));

当我断言res价值时,我没有得到正确的结果。调试将我追踪到Execution没有正确等待结果的地方。


调用的次数test function是正确的。但是日志记录混乱,最终结果没有结果fake


MMTTMM
浏览 203回答 2
2回答

慕雪6442864

我想你想要的是public static T Execute<T>(Func<T> func) where T : Task{&nbsp; &nbsp; return Policy.Handle<HttpRequestException>()&nbsp; &nbsp; &nbsp; &nbsp; .Or<TimeoutException>()&nbsp; &nbsp; &nbsp; &nbsp; .WaitAndRetryAsync(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 3,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; retryAttempt => TimeSpan.FromSeconds(Math.Pow(5, retryAttempt)),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (exception, timeSpan, retryCount, context) =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //do some logging&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; .ExecuteAsync(func).Wait();}在您的代码示例中,您调用func一次并返回它,然后在定义和调用策略之间,但不返回调用该策略的结果。如果你想避免,Wait我想你也可以这样做public static T Execute<T>(Func<T> func) where T : Task{&nbsp; &nbsp; return Policy.Handle<HttpRequestException>()&nbsp; &nbsp; &nbsp; &nbsp; .Or<TimeoutException>()&nbsp; &nbsp; &nbsp; &nbsp; .WaitAndRetryAsync(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 3,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; retryAttempt => TimeSpan.FromSeconds(Math.Pow(5, retryAttempt)),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (exception, timeSpan, retryCount, context) =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //do some logging&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; .ExecuteAsync(async () => await func());}
打开App,查看更多内容
随时随地看视频慕课网APP