2

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);
Anas Alweish
  • 2,818
  • 4
  • 30
  • 44
vico
  • 17,051
  • 45
  • 159
  • 315

4 Answers4

2

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0
async void DoTask() {
  string task = await returnString();
  Console.WriteLine(task);
}

Task<string> returnString() {
  // you code here
}

You can use async method to await Task execution

Marco Dal Zovo
  • 369
  • 2
  • 17
0

To answer the actual question. You either need to wait to get the results, or you need to do as Panagiotis Kanavos suggested, and await a task. You're overcomplicating threading, a common issue with all the bad examples out there.

Trey
  • 413
  • 4
  • 12
0

If you still want to use Task better approach is:

var result = taskThatReturns.GetAwaiter().GetResult();
xneg
  • 1,204
  • 15
  • 24