我有一个非常繁重的任务,可以在函数开始时运行,但稍后在函数中需要结果。
该函数需要几秒钟才能完成,因此没有理由不让任务尽早运行。在之间进行其他处理,以便稍后更短时间等待完成。
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
如何开始一个任务,然后在另一个时间点等待它完成。仅仅调用await analyzer.Parse();
是不够的。
我曾经在几年前某个地方读到过如何做,但是我现在在 Google 和 Stackoverflow 上无法找到任何相关内容了。
Task<IAnalyzerResult> analyzerTask = analyzer.Parse().Start(); ... IAnalyzerResult res = await analyzerTask;
- Fildor