Reputation: 1000
So I'm trying to come up with the right async overload that would correspond to this answer.
To give some context, I need to make asynchronous http calls to various places to check if a search is done, and later to download files. This system will often return various Http errors.
As has been written about many times, when HttpClient throws an error inside an async method it will throw a TaskCanceledException, cancel the task, and break any subsequent await (such as my await Task.WhenAll that comes later).
So, here's what I have so far. I'm stuck at this stage. The compiler tells me "Cannot convert lambda expression to type 'System.Threading.Task.Task' because it is not a delegate type"
I've looked at tons of SO questions and read a bunch of articles on MSDN about delegates and async / await and Task, Task<T>, Func<T>, Action, etc. and can't find out how I'm supposed to write this line:
var DownloadResponse = Retry.Do<HttpResponseMessage,TaskCanceledException>
(async ()=> await Client.GetAsync(URL,
HttpCompletionOption.ResponseHeadersRead),TimeSpan.FromSeconds(2),3);
Here's the async overload I wrote/modified that gets called
static async Task<T> Do<T, U>(
Task<T> action,
TimeSpan retryInterval,
int retryCount = 3)
where T : Task
where U : Exception
{
var exceptions = new List<U>();
for(int retry = 0; retry < retryCount; retry++)
{
try
{
return await action;
}
catch(Exception ex)
{
if(ex is U)
exceptions.Add(ex as U);
}
await Task.Delay(retryInterval);
}
throw new AggregateException(exceptions);
}
Upvotes: 0
Views: 1011
Reputation: 144136
It looks like action
should be a Func<Task<T>>
. Note you can also remove the type check of the exception.
static async Task<T> Do<T, U>(
Func<Task<T>> action,
TimeSpan retryInterval,
int retryCount = 3)
where U : Exception
{
var exceptions = new List<U>();
for(int retry = 0; retry < retryCount; retry++)
{
try
{
return await action();
}
catch(U ex)
{
exceptions.Add(ex);
}
catch(Exception ex) { }
await Task.Delay(retryInterval);
}
throw new AggregateException(exceptions);
}
Upvotes: 4