I've got a method that needs to PUT data to a web API. Sometimes the connection fails, so I needed a way to do retries, but if the retries fail, I still need to capture the exception and re-throw it.
I've got something that I "believe" is working, but I've got a stupid throw at the end. Is there a better, more concise way to do this when working with async tasks?
private const int TotalNumberOfAttempts = 10;
public static async Task<HttpResponseMessage> PutWithRetriesAsync(string url,
HttpContent content,
AuthenticationHeaderValue authenticationHeaderValue,
MediaTypeWithQualityHeaderValue mediaTypeWithQualityHeaderValue)
{
var numberOfAttempts = 0;
ExceptionDispatchInfo capturedException;
do
{
try
{
return await PutAsync(url, content, authenticationHeaderValue, mediaTypeWithQualityHeaderValue);
}
catch (AggregateException ex)
{
capturedException = ExceptionDispatchInfo.Capture(ex);
numberOfAttempts++;
}
} while (numberOfAttempts < TotalNumberOfAttempts);
if (capturedException != null)
{
capturedException.Throw();
}
throw new Exception("That will never be thrown");
}