Search code examples
taskconsole-applicationwaitc#-2.0

Should I use Task.Wait()?


Should I use taskThatReturns.Wait() in code below or I can omit it since according to my understanding taskThatReturns.Result will do wait anyway.

Task<string> taskThatReturns = new Task<string>(MethodThatReturns);
taskThatReturns.Start();
taskThatReturns.Wait();
Console.WriteLine(taskThatReturns.Result);

Solution

  • The call of Wait() before accessing Result is unnecessary.

    Examination of the reference code of Task and Task<TResult> shows that both the void Wait() method and the getter of the Result property eventually make their way into the method that does the actual waiting:

    internal bool InternalWait(int millisecondsTimeout, CancellationToken cancellationToken)
    

    Both code paths send identical parameter values to InternalWait - infinite wait and default cancellation token.

    If you call Wait before accessing Result, the code path inside the getter leading to InternalWait would be skipped, because the task is known to be completed. However, the net result would remain the same in both cases.

    Note: This answer intentionally ignores opportunities to optimize your code fragment.