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

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

问题描述

我有一个 async 方法:

public async Task<string> GenerateCodeAsync()
{
    string code = await GenerateCodeService.GenerateCodeAsync();
    return code;
}

我需要从同步方法中调用此方法.

I need to call this method from a synchronous method.

如何在不必复制 GenerateCodeAsync 方法的情况下执行此操作以使其同步工作?

How can I do this without having to duplicate the GenerateCodeAsync method in order for this to work synchronously?

更新

尚未找到合理的解决方案.

Yet no reasonable solution found.

但是,我看到 HttpClient 已经实现了这个 模式

However, I see that HttpClient already implements this pattern

using (HttpClient client = new HttpClient())
{
    // async
    HttpResponseMessage responseAsync = await client.GetAsync(url);

    // sync
    HttpResponseMessage responseSync = client.GetAsync(url).Result;
}

推荐答案

您可以访问任务的 Result 属性,这将导致您的线程阻塞,直到结果可用:

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;


注意:在某些情况下,这可能会导致死锁:您对 Result 的调用会阻塞主线程,从而阻止执行其余异步代码.您可以选择以下选项来确保不会发生这种情况:


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:

在线程池线程中显式执行异步方法并等待它完成:

explicitly execute your async method in a thread pool thread and wait for it to finish:

  string code = Task.Run(() => GenerateCodeAsync).Result;

并不意味着您应该在所有异步调用之后无意识地添加 .ConfigureAwait(false) !有关为什么以及何时应该使用 .ConfigureAwait(false) 的详细分析,请参阅以下博客文章:

This does not mean that you should just mindlessly add .ConfigureAwait(false) after all your async calls! For a detailed analysis on why and when you should use .ConfigureAwait(false), see the following blog post:

这篇关于同步调用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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