Raj
Raj

Reputation: 59

How to wait for to Task.Run to complete

I have a program that processes something like this

var t=Task.Run(()=>process());
while(!t.IsCompleted())
 Task.Delay(1000);
Console.WriteLine(t.Result);

Is there any other way to make the program wait till Task gets completed?

Upvotes: 2

Views: 15027

Answers (3)

Jasper Kent
Jasper Kent

Reputation: 3676

It happens automatically. You just need:

var t=Task.Run(()=>process());

Console.WriteLine(t.Result);

If t.Result is unavailable at first, the program will block at that point until the value has been calculated.

That said, if you just want to wait for the result, why run it as a task at all?

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062494

What you're doing here is essentially "sync over async". The wrong fix here would be to just... t.Wait() instead of your loop. However, really, you should try to make this code async, and use instead:

Console.WriteLine(await t);

Note that your Main method in C# can be async static Task Main() if needed.

However! There really isn't much point using Task.Run here - that's just taking up a pool thread, and blocking the current thread waiting on it. You aren't gaining anything from the Task.Run!

  • if process() is synchronous: just use Console.WriteLine(process())
  • if process() is asynchronous (returns a Task<T>/ValueTask<T>/etc): just use Console.WriteLine(await process())

Upvotes: 6

Related Questions