0

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);
}

1 Answer 1

4

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah removing the type check of the exception makes sense. I'll try this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.