ASP.NET MVC何時使用異步Action

在沒有使用異步Action以前,在Action內,好比有以下的寫法:編程

 

public ActionResult Index()
{
    CustomerHelper cHelper = new CustomerHelper();
    List<Customer> result = cHelper.GetCustomerData();
    return View(result);
}

 

以上,假設,GetCustomerData方法是調用第三方的服務,整個過程都是同步的,大體是:框架

 

→請求來到Index這個Action
→ASP.NET從線程池中抓取一個線程
→執行GetCustomerData方法調用第三方服務,假設持續8秒鐘的時間,執行完畢
→渲染Index視圖異步

 

在執行執行GetCustomerData方法的時候,因爲是同步的,這時候沒法再從線程池抓取其它線程,只能等到GetCustomerData方法執行完畢。async

 

這時候,能夠改善一下整個過程。異步編程

→請求來到Index這個Action
→ASP.NET從線程池中抓取一個線程服務於Index這個Action方法
→同時,ASP.NET又從線程池中抓取一個線程服務於GetCustomerData方法
→渲染Index視圖,同時獲取GetCustomerData方法返回的數據spa

 

因此,當涉及到多種請求,好比,一方面是來自客戶的請求,一方面須要請求第三方的服務或API,能夠考慮使用異步Action。線程

 

假設有這樣的一個View Model:設計

 

public class Customer
{
    public int Id{get;set;}
    public Name{get;set;}
}

 

假設使用Entity Framework做爲ORM框架。get

 

public class CustomerHelper
{
	public async Task<List<Customer>> GetCustomerDataAsync()
	{
		MyContenxt db = new MyContext();
		var query = from c in db.Customers
					orderby c.Id ascending
					select c;
		List<Customer>	result = awai query.ToListAsycn();
		return result;				
	}
}

 

如今就能夠寫一個異步Action了。同步

 

public async Task<ActionResult> Index()
{
	CustomerHelper cHelper = new CustomerHelper();
	List<Customer> result = await cHlper.GetCustomerDataAsync();
	return View(result);
}

 

Index視圖和同步的時候相比,並無什麼區別。

 

@model List<Customer>
@foreach(var customer in Model)
{
	<span>@customer.Name</span>
}

 

固然,異步還設計到一個操做超時,默認的是45秒,但能夠經過AsyncTimeout特性來設置。

 

[AsyncTimeout(3000)]
public async Task<ActionResult> Index()
{
	...
}

 

若是不想對操做超時設限。

 

[NoAsyncTimeout]
public async Task<ActionResult> Index()
{
	...
}

 

 

綜上,當涉及到調用第三方服務的時候,就能夠考慮使用異步Action。async和await是異步編程的2個關鍵字,async總和Action成對出現,而在調用異步方法以前要加上await關鍵字。

相關文章
相關標籤/搜索