Using Asynchronous Methods in ASP.NET MVC 4
asp.net mvc中的异步只能增加系统的性能,原来需要500个线程的,现在需要50个就够了,对一些常规的程序运行的时间上并没有减少,但是如何IO操作或者其他操作是非常耗时的,就可以使用异步来跳过,减少程序的反应时间
简单理解:
同步controller
public ActionResult GetSomething(){}
同步controller里面可以使用异步方法来加快速度,但是这种情况是在接下来的程序里不需要这个异步程序的返回值,或者很晚才需要这个异步返回的值
异步controller
public async Task(ActionResult> GetSomething(){}
异步controller是为了那些只写了异步的方法来设置的,比如某些方法只有异步的实现,没有同步的实现,而接下来的函数又需要这些异步的返回值,怎么办?只能await等待这些值返回,所以就需要使用async task await配对来调用异步的函数并等待他们返回,如果不需要返回值,那就不需要async task这个前缀了。由此可见,这个async task 是为了实现异步函数的同步实现的,其本身又是一个异步的task,可以被别人异步的执行,这样就好理解了
截取文章中的内容:什么时候用同步的方法,什么时候用异步的方法
Choosing Synchronous or Asynchronous Action Methods
This section lists guidelines for when to use synchronous or asynchronous action methods. These are just guidelines; examine each application individually to determine whether asynchronous methods help with performance.
In general, use synchronous methods for the following conditions:
- The operations are simple or short-running.
- Simplicity is more important than efficiency.
- The operations are primarily CPU operations instead of operations that involve extensive disk or network overhead. Using asynchronous action methods on CPU-bound operations provides no benefits and results in more overhead.
In general, use asynchronous methods for the following conditions:
- You're calling services that can be consumed through asynchronous methods, and you're using .NET 4.5 or higher.
- The operations are network-bound or I/O-bound instead of CPU-bound.
- Parallelism is more important than simplicity of code.
- You want to provide a mechanism that lets users cancel a long-running request.
- When the benefit of switching threads out weights the cost of the context switch. In general, you should make a method asynchronous if the synchronous method waits on the ASP.NET request thread while doing no work. By making the call asynchronous, the ASP.NET request thread is not stalled doing no work while it waits for the web service request to complete.