-2

For example, what is the difference between

        Task<DataSet> DBTask = Task.Run (() => DBHelper.DbTest ());
        Task<Boolean> CheckTimeTask = Task.Run (() => Module.CheckTime ());
        Task.WhenAll (DBTask, CheckTimeTask); // <-- no wait?
        if (!CheckTimeTask.Result || DBTask.Result == null)
        {
            Close ();
        }   

and

        Task<DataSet> DBTask = Task.Run (() => DBHelper.DbTest ());
        Task<Boolean> CheckTimeTask = Task.Run (() => Module.CheckTime ());
        Task.WhenAll (DBTask, CheckTimeTask).Wait (); // <-- wait ?
        if (!CheckTimeTask.Result || DBTask.Result == null)
        {
            Close ();
        }  

It does seem both are waiting until the result is returned? I could not figure out the differences, so which is better?

TRX
  • 465
  • 1
  • 8
  • 17
  • As presented, your question makes no sense, because `Task.WhenAll()` does _nothing_ other than return a `Task` object that represents the asynchronous completion of all the `Task` objects passed to it. Your code discards the returned `Task` object, meaning that `Task` remains unobserved and has no effect at all on the program. A correctly written program would use `await` on that statement, and the duplicate explains exactly what the difference between that and using `Wait()` is. – Peter Duniho Dec 30 '20 at 02:49

1 Answers1

2

Task.WhenAll is an asynchronous function that returns a new Task that will complete once all subsequent tasks are completed.

Task.WhenAll().Wait actually awaits for all subsequent tasks to be completed before moving to the next line of code.

In your example, I’m sure you are encountering a race condition where both samples are producing the same debug results. However, Task.WhenAll by itself without .Wait is in fact asynchronous and will not halt further code execution if subsequent tasks are not yet finished.

Here is some additional informative links:

Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35
S. Walker
  • 2,129
  • 12
  • 30