I have the following async method, which is a simpler wait and retry in case of failures:
public async Task RetryAsync(Func<Task> _action, int _ms = 1000, int _counter = 3) {
while (true) {
try {
await _action();
return; // success!
}
catch {
if (--_counter == 0)
throw;
await Task.Delay(_ms);
}
}
}
To, in theory, be called like this:
await RetryAsync(async () => {
_newID = myDBFunction();
}, 300);
Since the function passed to the RetryAsync method does not contain any await, then obviously this gets the warning:
This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
... and changing the calling code to this fixes the problem:
await RetryAsync(async () => {
await Task.Run(() => _newID = myDBFunction(););
}, 300);
Is there any other way to achieve parallelism for this simple case besides using Task.Run()? Any disadvantage you see to the latest code with Task.Run() on it?
async
method, if in reality it's notasync
? – Ofir WinegartenFunc<Task>
signature, but the implementation, doesn't have to beasync
. You can as you said, just useTask.Run
without theawait
andasync
- What's wrong with that? – Ofir WinegartenRetryAsync
, Just remove theasync
andawait
.await RetryAsync(() => Task.Run(() => _newID = myDBFunction()), 300);
– Ofir Winegarten