I have an async
method:
public async Task<string> GenerateCodeAsync()
{
string code = await GenerateCodeService.GenerateCodeAsync();
return code;
}
I need to call this method synchronously, from another synchronous method.
How can I do this?
ベストアンサー1
You can run the method in a thread pool thread and use the task's awaiter to block the calling thread until the asynchronous operation has completed:
string code = Task.Run(() => GenerateCodeAsync()).GetAwaiter().GetResult();
Why is .Result
not good enough?
You might be tempted to just access the Result
property of the task to achieve the same result:
string code = GenerateCodeAsync().Result;
This naive approach, however, has two drawbacks:
In some cases this leads to a deadlock: Your call to
Result
blocks the main thread, thereby preventing the remainder of the async code to execute. This can be avoided by adding.ConfigureAwait(false)
at the right places, but doing this correctly is not trivial.We avoid this issue by calling
Task.Run
to execute the asynchronous method in a thread pool thread..Result
(or.Wait()
for tasks without a return value) will wrap any Exception that may be thrown in your asynchronous method in anAggregateException
.We avoid this issue by calling
.GetAwaiter().GetResult()
instead.