Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between await Task<T> and Task<T>.Result?

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?

like image 205
Yawar Murtaza Avatar asked Dec 13 '14 22:12

Yawar Murtaza


People also ask

What is the difference between await and result?

Result() it blocks the thread until a result is returned before continuing to the next line of code. When you use await you are also awaiting an synchronous call to complete before the code following t (continuation step).

What is the difference between task and async task?

Async methods are intended to be non-blocking operations. An await expression in an async method doesn't block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.

Should I return task or await?

Simply return the Task is enough. "when you hit the await, the control flow is returned to the calling method" -- The control flow might be returned to the calling method, particularly it won't return when the awaited task is already complete.

What happens if you don't await a task?

If you don't await the task or explicitly check for exceptions, the exception is lost. If you await the task, its exception is rethrown. As a best practice, you should always await the call. By default, this message is a warning.


1 Answers

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.

like image 127
Stephen Cleary Avatar answered Oct 10 '22 02:10

Stephen Cleary