public void DoStuff()
{
// I want to be able to call the method DoAsynckStuff and wait for the result.
// I know that's not a usual thing to do
// Usually also this will be async method and then just await the result.
// I need this to be something like
var resultTask = DoAsynckStuff();
resultTask.Wait();
var result = resultTask.Result;
//.....
}
public async Task<string> DoAsynckStuff()
{
//...
}
抱歉,我是異步等待的新手。我需要的是等待特定異步方法的結果。我不能使方法異步,因為它會導致呼叫該方法的方法出現一些問題。
我已經在 Task 上嘗試了 Wait 方法,就像在代碼示例中一樣。但是任務狀態會一直是“等待激活”。
我也嘗試resultTask.Start()在等待方法之前呼叫該方法,但這會拋出
System.InvalidOperationException: Start may not be called on a promise-style task.
也會result.RunSynchronously()拋出該例外。
我還查看
uj5u.com熱心網友回復:
聽起來您正在使用同步背景關系(如 WinForms 或 WPF)運行應用程式。
無論如何,同步運行異步代碼的正確方法是啟動一個新執行緒并等待它。
var result = Task.Run(() => DoAsyncStuff()).Result;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/515707.html
