The first is prepared to do this asynchronously, that is, the code begins to do and continues its normal "life" regardless of the execution of this query and when she finishes the code will be notified of this.
In the past this was complicated to do in C#, although feasible. With C# 5 it was much easier because the compiler mounts the state machine that controls this stream. And the class Task
helps in this by even controlling whether it will run in thread separate or not. Although in the current form it is not proper to apply the asynchronicity since it lacks the modifier async
in the method.
When you want to run the task asynchronously, you must do this through a class representing a task, that is, a Task
. Then you will receive a task that will contain the result at the proper time, instead of pure result.
Obviously the asynchronous execution has the advantage of not blocking the application. If it takes time to generate this list the application will continue running normal and resume there when the list is generated. The second method will block execution until the list is finished.
Size is not important but the time it will take to perform the task. It is often said that if the task takes less than 50ms it is better to execute synchronously even, after all the assichricity has its cost.
Except this task case is very fast I see only advantages in using asynchronous form. Of course the code gets slightly more complex, but it’s minimal. What can really get in the way is if you need to debug. But the ideal is to make it work well synchronously first, this avoids a bit of the problem. Of course, if you have problems debugging the asynchronicity process, it’s really chipped. But it’s improved with Visual Studio 2015. Debugging asynchronous tasks can be more laborious and confusing in certain circumstances.
Eventually the use of ToListAsync()
can be interesting there. But it depends on how this method will be used and what this ToList()
current is doing. It’s just an assumption.
To learn more about the resource see that question. I gave an answer there that illustrates well how it works. There are other answers with different approaches that will help you asynchronicity. Other very good question with more focus on ASP.NET can be seen here.
By way of curiosity, I don’t know if it was just an example but the variable is totally unnecessary in this method.
Ask me a question, the app is responsive only after
return Task.FromResult(query);
or so I callTask<List<Product>> GetAllProductsAsync()
?– rubStackOverflow