异步调用同步方法 [英] Calling async method synchronously
问题描述
我有一个异步
方法:
public async Task<string> GenerateCodeAsync()
{
string code = await GenerateCodeService.GenerateCodeAsync();
return code;
}
我需要从一个同步的方法调用此方法。
I need to call this method from a synchronous method.
我怎么能做到这一点,而不必复制生成codeAsync
方法,为了这个同步工作?
How can I do this without having to duplicate the GenerateCodeAsync
method in order for this to work synchronously?
推荐答案
您可以访问结果
任务,这将导致你的线程阻塞,直至结果的财产可用:
You can access the Result
property of the task, which will cause your thread to block until the result is available:
string code = GenerateCodeAsync().Result;
请注意:在某些情况下,这可能会导致死锁:您对结果呼叫
块为主线,从而$ P $ pventing的异步$ C的剩余部分$ C来执行。您有以下选项,以确保不会发生这种情况:
Note: In some cases, this might lead to a deadlock: Your call to Result
blocks the main thread, thereby preventing the remainder of the async code to execute. You have the following options to make sure that this doesn't happen:
- 添加
.ConfigureAwait(假)
到您的库法的或的 -
中明确线程池中的线程中执行的异步方法并等待它完成:
- Add
.ConfigureAwait(false)
to your library method or explicitly execute your async method in a thread pool thread and wait for it to finish:
string code = Task.Run(GenerateCodeAsync).Result;
这篇关于异步调用同步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!