Ren*_*nte 3 c# asynchronous task async-await
我有一个非常艰巨的任务,可以在函数的开头运行,但随后需要在函数的稍后一点返回结果。
该功能需要花费几秒钟才能完成,并且没有理由不让任务更早运行。在其间进行其他处理,然后等待更短的时间来完成。
analyzer.Parse()是一个Task<IAnalyzerResult>。
analyzer = new ExprAnalyzer(expr);
//start the task
analyzer.Parse().Start();
// [...] Do other stuff
// Now I need analyzer.Parse() to have finished
IAnalyzerResult res = await analyzer.Parse() //this obviously doesn't work.
// [...] Process the result
Run Code Online (Sandbox Code Playgroud)
如何启动任务,然后在其他时间等待任务完成。简单地打电话await analyzer.Parse();不会成功。
几年前,我读过有关如何做的信息,但现在在Google和Stackoverflow上找不到任何东西。
获取返回的任务:
Task<IAnalyzerResult> t = analyzer.Parse();
Run Code Online (Sandbox Code Playgroud)
然后,等待其结果:
IAnalyzerResult res = await t;
Run Code Online (Sandbox Code Playgroud)