Prophet Lamb
Prophet Lamb

Reputation: 610

Start task, later wait for completion

I have a pretty intensive task, that I can run at the beginning of a function, but I then need the result at a later point in the function.

The function takes a few seconds to complete and there is no reason not to let the task run earlier. Do other processing in between, to then wait a shorter amount of time for the completion.

analyzer.Parse() is a 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

How do I start a task and then wait for it to complete at another point in time. Simply calling await analyzer.Parse(); wont do the trick.

I read how to do it somewhere years ago, but I couldn't find anything on Google and Stackoverflow anymore.

Upvotes: 3

Views: 1208

Answers (1)

dcg
dcg

Reputation: 4219

Get the returned Task:

Task<IAnalyzerResult> t = analyzer.Parse();

Then, await its result:

IAnalyzerResult res = await t;

Upvotes: 6

Related Questions