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?
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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With