gpt4 book ai didi

c# - 同步调用第三方异步任务方法

转载 作者:太空宇宙 更新时间:2023-11-03 17:24:27 25 4
gpt4 key购买 nike

我正在阅读数百个关于 await/async 的答案,但对于这个简单的问题仍然没有答案。有一个可等待的方法,是别人写的,需要等到它完成。

// 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 线程、任何其他线程...出于安全原因,必须以这种方式解决。

问题是async方法的返回值是Task,没有等待的.Result标签。
还有其他的无死锁方案吗?

最佳答案

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

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

关于c# - 同步调用第三方异步任务方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27869403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com