调用第三方异步任务同步方法 [英] Calling a 3rd party async Task method synchronously

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

问题描述

我在阅​​读上百篇的答案约等待 / 异步,但仍然没有回答这个简单的题。
有一个awaitable方法,别人写,这是必要的,以等待直到它完成

I'm reading hundreds of answers about await/async, but there is still no answer to this simple question. There is an awaitable method, written by someone else and it is necessary to wait till it finishes.

// cannot be changed
public async Task ThirdPartyAsync(...)
{
    // calls other awaitable methods
    // takes few seconds
}

// I'd like something like this
public void MyPatientCallingMethod(...)
{
    // 1. call the method
    ThirdPartyAsync(...);

    // 2. wait for ThirdPartyAsync to finish (I don't care how long) 

    // 3. return after
    return;
}

是的,我知道,这将阻止主线程,UI线程,任何其他线程...
它为安全起见,用此方式解决。

Yes, I know, it will block the main thread, the UI thread, any other thread... It has to be solved this way for safety reasons.

问题是异步方法工作的返回值并没有。结果标记等。结果
是否有任何其他无死锁的解决方案?

The problem is the return value of the async method is Task, and there is no .Result tag to wait for.
Is there any other deadlock-free solution?

推荐答案

您可以使用的 Task.Wait() 以阻止该任务。

You can use Task.Wait() to block on the task.

// call the method and wait for ThirdPartyAsync to finish (I don't care how long) 
ThirdPartyAsync(...).Wait();

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

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