If I have a .NET 4.5 asynchronous task method, for example:
public async Task<String> GetData()
(...)
return await MyObject.GetSomethingAsynchronous();
And then somewhere else in a synchronous thread (e.g. a non-async method), I call this:
String myString = MyObject.GetData().Result;
Is this safe to do or bad practice?
Calling
Task.Resultis generally not recommended. A better solution is toawaittheTaskand change the containing method to beasync, allowing the asynchronous code to grow up through the code base.There are two problems with
Task.Resultas compared toawait(other than the fact that it blocks rather than asynchronously waiting):Taskneeds a particular thread (e.g., a UI thread) to complete but that thread is blocked on thatTask. I explain this in more detail on my blog.asyncmethod will be wrapped in anAggregateException, which makes exception handling much more complex.awaitwill unwrap the underlying error, allowing you to use a much more naturalcatch(MyExceptionType).