I\'m in the process of updating a library that has an API surface that was built in .NET 3.5. As a result, all methods are synchronous. I can\'t change the API (i.e., conver
So I'm left with how to best call async methods in a synchronous way.
First, this is an OK thing to do. I'm stating this because it is common on Stack Overflow to point this out as a deed of the devil as a blanket statement without regard for the concrete case.
It is not required to be async all the way for correctness. Blocking on something async to make it sync has a performance cost that might matter or might be totally irrelevant. It depends on the concrete case.
Deadlocks come from two threads trying to enter the same single-threaded synchronization context at the same time. Any technique that avoids this reliably avoids deadlocks caused by blocking.
Here, all your calls to .ConfigureAwait(false) are pointless because you are not awaiting.
RunSynchronously is invalid to use because not all tasks can be processed that way.
.GetAwaiter().GetResult() is different from Result/Wait() in that it mimics the await exception propagation behavior. You need to decide if you want that or not. (So research what that behavior is; no need to repeat it here.)
Besides that, all these approaches have similar performance. They will allocate an OS event one way or another and block on it. That's the expensive part. I don't know which approach is absolutely cheapest.
I personally like the Task.Run(() => DoSomethingAsync()).Wait(); pattern because it avoids deadlocks categorically, is simple and does not hide some exceptions that GetResult() might hide. But you can use GetResult() as well with this.