【发布时间】:2020-03-15 04:08:36
【问题描述】:
我有一个非常密集的任务,我可以在函数的开头运行它,但我需要在函数的稍后位置得到结果。
该功能需要几秒钟才能完成,没有理由不让任务提前运行。在其间进行其他处理,然后等待更短的时间完成。
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; -
请不要edit answers to change the results。如果您认为答案有问题,请发表评论。还有you're wrong
标签: c# asynchronous async-await task