问题
We currently are building an MVC 5 application, the application makes calls to a Business Layer which calls the database, there is no WCF or Web Api service. All of our controllers are currently not async, i've been looking into task/async and wanted to know if it's becoming common to make all Actions in a Controller async? For us, all actions are requesting the business layer to read data via Entity Framework, so would it make sense to change them all to asnyc? Or it is really only helpful when there is a middle layer, like a WCF or Web API service which might involve network latency that it's worth it?
回答1:
All async does is allow a thread that is in a wait-state be returned to the thread pool to field other operations. When whatever operation the original thread was waiting on finishes, a thread is requested back from the thread pool to finish the overarching task. Because the thread must be waiting, certain operations like making a request over HTTP to an API are ideal candidates for async while other operations like complex calculations and other CPU-bound work are completely inappropriate for async.
Now, since your question is regarding database queries, the answer is it depends. For example, if your database happened to be on the same server as your website (which is totally not a good idea BTW) async wouldn't do much for you. There may be some waiting, but it's going to be miniscule to the point where it would probably take longer to pass the threads around than it would to just hold the thread until the database finishes its work. Now, if you're doing things right and your database is on a remote server, network latency starts to come into play. A database on an internal network may still not benefit much from async, since the latency would still probably be very low, but async could still potentially help some. If your database is on an external network, though, then async would definitely be warranted as latency would be much higher.
Still, it's probably better err on the side of using async than not. Even if latency is low, that may not always be the case. And if your network is getting hammered, having everything set up as async will give your web server some valuable leeway to field requests where it otherwise might deadlock under the load.
来源:https://stackoverflow.com/questions/26552327/mvc-should-everything-be-async