2

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?

pinkfloydx33
  • 11,863
  • 3
  • 46
  • 63
Raj
  • 59
  • 1
  • 10
  • 4
    What's your purpose in using `Task.Run` in the first place? You're effectively asking for another thread to do some work for you because your thread's going to be busy - and then immediately turning around and saying there's no work for your thread to do until that other thread is finished. Why not call `process()` directly and use the thread you already have? – Damien_The_Unbeliever May 21 '20 at 09:09
  • This is wrapped in a synchronous method. Task is the only way I felt. Here process is an async method. – Raj May 21 '20 at 10:19
  • You may do `var t=Task.Run(()=>process()); t.Wait(); ConsoleWriteLine(t.Result);` – user007 Oct 19 '20 at 20:01

3 Answers3

6

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())
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

You have different options:
Asynchronous programming with async and await
Task.Wait
Task<TResult>.Result

Patrick Beynio
  • 788
  • 1
  • 6
  • 13
0

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?

Jasper Kent
  • 3,546
  • 15
  • 21