Synchronously call asynchronous methods
Suppose there is an asynchronous method, say GenerateCodeAsync()
, which returns a task. To call this method synchronously, you need to find a way to coordinate the synchronous and asynchronous code.
One solution is to run the asynchronous method in a thread pool thread and use awaiter
to block the thread until the operation completes:
<code class="language-csharp">string code = Task.Run(() => GenerateCodeAsync()).GetAwaiter().GetResult();</code>
Disadvantages of using .Result directly
Direct access to Result
properties may result in:
Result
blocks the main thread, preventing asynchronous code from executing. AggregateException
. To avoid these problems, GetAwaiter().GetResult()
method:
The above is the detailed content of How Can I Synchronously Call an Asynchronous Method in C# Without Deadlocks?. For more information, please follow other related articles on the PHP Chinese website!