1

I found some ways to call an async method on a sync method, but I don't know what is the best way in .net core and why?

DebugLog.Log(ex.ToString()).GetAwaiter();
System.Threading.Tasks.Task.Run(async () => await DebugLog.Log(ex.ToString()));
DebugLog.Log(ex.ToString()).RunSynchronously();
DebugLog.Log(ex.ToString()).ConfigureAwait(default);
namdar
  • 63
  • 2
  • 6
  • see this: https://stackoverflow.com/questions/9343594/how-to-call-asynchronous-method-from-synchronous-method-in-c – Majid Ramezankhani Sep 06 '21 at 06:42
  • Does this answer your question? [How to call asynchronous method from synchronous method in C#?](https://stackoverflow.com/questions/9343594/how-to-call-asynchronous-method-from-synchronous-method-in-c) – Johnathan Barclay Sep 06 '21 at 09:14

1 Answers1

0

I don't know what is the best way in .net core and why?

There is no best way. If there was, then everyone would just use that.

There are a variety of approaches, each with their own drawbacks. The two most common are:

  1. GetAwaiter().GetResult() (i.e., direct blocking) - can deadlock.
  2. Task.Run(...).GetAwaiter().GetResult() (i.e., block a thread pool thread) - doesn't work if the ... requires the current context.

RunSynchronously should never be used.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810