83
public async Task<string> GetName(int id)
{
    Task<string> nameTask = Task.Factory.StartNew(() => string.Format("Name matching id {0} = Developer", id));
    return nameTask.Result;
}

In above method return statement I am using the Task<T>.Result property.

public async Task<string> GetName(int id)
{
     Task<string> nameTask = Task.Factory.StartNew(() => string.Format("Name matching id {0} = Developer", id));
     return await nameTask;
}

Here I am using await Task<T>. I wont be wrong if I think that await will release the calling thread but Task<T>.Result will block it, would it be right?

3dGrabber
  • 4,710
  • 1
  • 34
  • 42
Yawar Murtaza
  • 3,655
  • 5
  • 34
  • 40
  • 2
    Since the second code has no continuation - you gain nothing. in the first code you just mark the method async but you don't await. – Royi Namir Dec 13 '14 at 22:29
  • To learn more about `async-await` take a look at the articles on [my `async-await`curation](http://curah.microsoft.com/45553/asyncawait-general). – Paulo Morgado Dec 13 '14 at 23:43
  • @RoyiNamir, isn't your statement incorrect? The first method gains nothing by using `async` as the method blocks the calling thread. However, the second method should yield the current thread and not block until the task is set into a completion state. – Matt Jan 03 '18 at 09:48
  • @MattWolf - I agree that the second method will have a benefit to whatever calls it, by letting it yield control back to the caller while the Task finishes. – Don Cheadle Jul 01 '18 at 17:15

2 Answers2

106

I wont be wrong if I think that await will release the calling thread but Task.Result will block it, would it be right?

Generally, yes. await task; will "yield" the current thread. task.Result will block the current thread. await is an asynchronous wait; Result is a blocking wait.

There's another more minor difference: if the task completes in a faulted state (i.e., with an exception), then await will (re-)raise that exception as-is, but Result will wrap the exception in an AggregateException.

As a side note, avoid Task.Factory.StartNew. It's almost never the correct method to use. If you need to execute work on a background thread, prefer Task.Run.

Both Result and StartNew are appropriate if you are doing dynamic task parallelism; otherwise, they should be avoided. Neither is appropriate if you are doing asynchronous programming.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • Thank you Stephen Cleary and Yuval Itzchakov for additional knowledge on this. – Yawar Murtaza Jan 08 '15 at 22:14
  • and is there any difference of getting a result after `await Task.WhenAll(task1, task2)`? `await task1` vs `task1.Result`? awaiting `WhenAll` should have done all work with threads already, right? – demo Apr 18 '19 at 13:13
  • 1
    @demo: I prefer `await` for two reasons: 1) it avoids `AggregateException` wrappers, and 2) it's more forgiving of code changes - i.e., if someone changes the method earlier and now the task is no longer complete. – Stephen Cleary Apr 18 '19 at 15:24
6

I wont be wrong if I think that await will release the calling thread but Task.Result will block it, would it be right?

You're correct, as long as the task hasn't completed synchronously. If it did, using either Task.Result or await task will execute synchronously, as await will first check if the task has completed. Otherwise, if the task hasn't completed, it will block the calling thread for Task.Result, while using await will asynchronously wait for the tasks completion. Another thing that differs is exception handling. While the former will propagate an AggregationException (which may contain one or more exceptions), the latter will unwrap it and return the underlying exception.

As a side note, using asynchronous wrappers over sync methods is bad practice and should be avoided. Also, using Task.Result inside an async method is a cause for deadlocks and should also be avoided.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • 3
    how can a deadlock happen in this "using Task.Result inside an async method is a cause for deadlocks", can you elaborate? – Deepak May 07 '21 at 13:22
  • Yuval, the link to your side note is dead. Do you have another resource? Or could you elaborate a bit about what the link was discussing? – Metro Smurf Feb 10 '23 at 14:45
  • 1
    @MetroSmurf I fixed the link. Here is the direct link: https://devblogs.microsoft.com/pfxteam/should-i-expose-asynchronous-wrappers-for-synchronous-methods/ – Yuval Itzchakov Feb 10 '23 at 20:45
  • @Deepak Due to the way SynchronizationContext works, it captures the current context before marshaling control back to the caller when it hits an `await`. Blocking with Task.Result means that when the callback tries to execute on that context once ready, it'll be forever locked waiting since .Result blocks. There many questions on SO explaining this phenomenon. – Yuval Itzchakov Feb 11 '23 at 10:04