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()
{
//...
}抱歉,我刚开始异步等待。我需要的是等待特定异步方法的结果。我无法使方法异步,因为它将导致调用该方法的方法出现一些问题。
我已经尝试过任务上的等待方法,就像在代码示例中一样。但是任务状态总是“等待激活”。
我还尝试在等待方法之前调用方法resultTask.Start(),但这将引发
System.InvalidOperationException: Start may not be called on a promise-style task.另外,result.RunSynchronously()将抛出该异常。
我也看过this article和其他一些东西,但没有得到结果
发布于 2022-10-16 22:47:52
听起来,您正在使用同步上下文运行应用程序,比如WinForms或WPF。
无论如何,同步运行异步代码的正确方法是启动一个新线程并等待它。
var result = Task.Run(() => DoAsyncStuff()).Result;发布于 2022-10-16 22:51:53
试着做这样的事情:
void Main()
{
var resultTask = Task.Run(() => DoAsyncStuff().Result );
resultTask.Wait();
Console.WriteLine(resultTask);
}
// You can define other methods, fields, classes and namespaces here
public async Task<string> DoAsyncStuff()
{
string output = "Task Complete";
Thread.Sleep(2000);
return output;
}这一产出如下:
Task Complete

https://stackoverflow.com/questions/74091123
复制相似问题