我遇到Polly问题,导致线程冻结。 如您所见,GetData()方法将引发异常。我想做的是在DoStuff()的GetData()方法中发生异常时继续执行Dostuff1和2。但是似乎在重试了polly之后,它只是卡住了,什么也不做...
我该如何解决?
private async Task StartUp()
{
await DoStuff());
// await next task DoStuff1();
// await next task DoStuff2();
}
private async Task DoStuff()
{
var data= await Task.WhenAll(Task.Run(() => GetData()));
// Do stuff with the data
}
private async Task<Data> GetData()
{
//read filepaths from file.
var tasks = filePaths
.Select(f => polly.MyPolicy().Execute(() => ReadDataFromCSV()))
.ToArray();
Return await tasks;
}
private Dictionary<string, DateTime?> ReadDataFromCSV()
{
///Throw exception....
}
public PolicyForGetData()
{
return Policy
.Handle<Exception>()
.WaitAndRetry(
retryCount: 2,
sleepDurationProvider: t => TimeSpan.FromSeconds(5),
onRetry: (ex, t, i, c) => {
Console.WriteLine(ex.Message);
}
);
}
答案 0 :(得分:1)
我认为您误会了Polly的举止。假设GetData()
总是抛出,那么您的应用程序将像这样
StartUp()
方法中,该方法可防止DoStuff1()
和DoStuff2()
被叫。例如。该程序的输出:
class Program
{
static void Main(string[] args)
{
try
{
Policy
.Handle<Exception>()
.WaitAndRetry(
retryCount: 2,
sleepDurationProvider: t => TimeSpan.FromSeconds(5),
onRetry: (ex, t, i, c) => {
Console.WriteLine("OnRetry");
}
)
.Execute(() => ErrorMethod());
Console.WriteLine("We never get here");
}
catch (Exception)
{
Console.WriteLine("Exception Handler");
}
}
private static void ErrorMethod()
{
throw new InvalidOperationException("Badness");
}
}
是
OnRetry
OnRetry
Exception Handler