我正在尝试找到为 Polly Policy 编写扩展方法的最佳方法
我有以下
public static async Task<IPollyDto> RunAsync(this IPolicy dtoClass, Func<Task<IDto>> action)
{
return
await Policy
.Handle<ApiException>(ex => ex.StatusCode == HttpStatusCode.RequestTimeout)
.RetryAsync(3,
async (exception, retryCount) => await Task.Delay(200))
.ExecuteAsync(async () => await action.Invoke().ConfigureAwait(false))
.ConfigureAwait(false);
}
public interface IPollyDto {}
public interface IPolicy {}
然后我按如下方式调用代码
public class DtoTest : IPollyDto
{
}
public class TestA
{
public static async Task<DtoTest> GetItem(string datasetName)
{
return await Task.Run(() => new DtoTest()) ;
}
}
public class PollyTest : IPolicy
{
public async Task<DtoTest> TestMe(string dataset)
{
return (DtoTest) await this.RunAsync(() => Task.Run(() => (IPollyDto) TestA.GetItem(dataset)));
}
}
我在解析类型时出错。
您在this.RunAsync(() => Task.Run(() => (IPollyDto) TestA.GetItem(dataset)))
通话中缺少async-await
。将其更改为:
this.RunAsync(() => Task.Run(async () => (IPollyDto)(await TestA.GetItem(dataset))));
或者只是:
this.RunAsync(async () => (IPollyDto)(await TestA.GetItem(dataset)))