I have a generic method for executing an asynchronous tasks in synchronous context with retries.
public static T RunWithRetries<T>(Task<T> task)
{
while(...) // 3 attempts
{
try
{
task.GetAwaiter().GetResult();
}
catch
{
// sleep & retry later in case of some exceptions, for example 429
}
}
}
Then I'm passing any method from asynchronous API to run it like this.
SyncHelper.RunWithRetries(externalAPI.UploadAsync(fileRequest, fileStream));
The problem is that it works unless an exception happened during the request and we need to re-try. If an error happens, all subsequent retries are also throwing the same exception. So, my questions are
- Is this happening because of the fileStream object? It's in the using statement, so it's not being disposed for sure. Can the stream position after first upload attempt be a problem?
- Is it normal that the same Task object is being retried? Should I change the way I'm doing it to something better?