异步调用同步方法 [英] Calling async method synchronously

查看:144
本文介绍了异步调用同步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个异步方法:

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:

  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆