CacheManager icon indicating copy to clipboard operation
CacheManager copied to clipboard

Avoid using async functions from synchronous code

Open pergardebrink opened this issue 5 years ago • 3 comments

This changes the retrytimeout to use Thread.Sleep as we cannot use Task.Delay in this context due to risk of deadlocks.

pergardebrink avatar Feb 17 '20 10:02 pergardebrink

I don't think it is a good idea to use Thread.Sleep. That would suspend the thread which might run many tasks in the host application and could cause even more harm.

I think I'd either use Task.Delay(x).GetAwaiter().GetResult() or remove the delay between retries all together because of possibly too many side effects.

MichaCo avatar Feb 17 '20 13:02 MichaCo

I think I'd either use Task.Delay(x).GetAwaiter().GetResult() or remove the delay between retries all together because of possibly too many side effects.

Wouldn't that also block the current thread in the same way as a Thread.Sleep would do, as the GetResult() call is blocking the current thread until the Task ends?

pergardebrink avatar Feb 17 '20 18:02 pergardebrink

I think I'd either use Task.Delay(x).GetAwaiter().GetResult() or remove the delay between retries all together because of possibly too many side effects.

Wouldn't that also block the current thread in the same way as a Thread.Sleep would do, as the GetResult() call is blocking the current thread until the Task ends?

Looked a bit more into this for a reference for my reasoning here. David Fowler at Microsoft has a great collection on guidance on async programming. He has a section on "sync over async" about that invoking an async method (for example Task.Delay) and then blocking the thread while waiting (GetAwaiter().GetResult()) for it to complete could be worse than just calling the synchronous version (Thread.Sleep): https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md#warning-sync-over-async

pergardebrink avatar Aug 05 '20 23:08 pergardebrink