ASP.NET MVC使用異步Action的方法
在沒(méi)有使用異步Action之前,在Action內(nèi),比如有如下的寫法:
public ActionResult Index() { CustomerHelper cHelper = new CustomerHelper(); List<Customer> result = cHelper.GetCustomerData(); return View(result); }
以上,假設(shè),GetCustomerData方法是調(diào)用第三方的服務(wù),整個(gè)過(guò)程都是同步的,大致是:
→請(qǐng)求來(lái)到Index這個(gè)Action
→ASP.NET從線程池中抓取一個(gè)線程
→執(zhí)行GetCustomerData方法調(diào)用第三方服務(wù),假設(shè)持續(xù)8秒鐘的時(shí)間,執(zhí)行完畢
→渲染Index視圖
在執(zhí)行執(zhí)行GetCustomerData方法的時(shí)候,由于是同步的,這時(shí)候無(wú)法再?gòu)木€程池抓取其它線程,只能等到GetCustomerData方法執(zhí)行完畢。
這時(shí)候,可以改善一下整個(gè)過(guò)程。
→請(qǐng)求來(lái)到Index這個(gè)Action
→ASP.NET從線程池中抓取一個(gè)線程服務(wù)于Index這個(gè)Action方法
→同時(shí),ASP.NET又從線程池中抓取一個(gè)線程服務(wù)于GetCustomerData方法
→渲染Index視圖,同時(shí)獲取GetCustomerData方法返回的數(shù)據(jù)
所以,當(dāng)涉及到多種請(qǐng)求,比如,一方面是來(lái)自客戶的請(qǐng)求,一方面需要請(qǐng)求第三方的服務(wù)或API,可以考慮使用異步Action。
假設(shè)有這樣的一個(gè)View Model:
public class Customer { public int Id{get;set;} public Name{get;set;} }
假設(shè)使用Entity Framework作為ORM框架。
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; } }
現(xiàn)在就可以寫一個(gè)異步Action了。
public async Task<ActionResult> Index() { CustomerHelper cHelper = new CustomerHelper(); List<Customer> result = await cHlper.GetCustomerDataAsync(); return View(result); }
Index視圖和同步的時(shí)候相比,并沒(méi)有什么區(qū)別。
@model List<Customer> @foreach(var customer in Model) { <span>@customer.Name</span> }
當(dāng)然,異步還設(shè)計(jì)到一個(gè)操作超時(shí),默認(rèn)的是45秒,但可以通過(guò)AsyncTimeout特性來(lái)設(shè)置。
[AsyncTimeout(3000)] public async Task<ActionResult> Index() { ... }
如果不想對(duì)操作超時(shí)設(shè)限。
[NoAsyncTimeout] public async Task<ActionResult> Index() { ... }
綜上,當(dāng)涉及到調(diào)用第三方服務(wù)的時(shí)候,就可以考慮使用異步Action。async和await是異步編程的2個(gè)關(guān)鍵字,async總和Action
到此這篇關(guān)于ASP.NET MVC使用異步Action的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持。
相關(guān)文章:
1. ASP.NET MVC通過(guò)勾選checkbox更改select的內(nèi)容2. ASP.NET MVC實(shí)現(xiàn)區(qū)域或城市選擇3. ASP.NET MVC前臺(tái)動(dòng)態(tài)添加文本框并在后臺(tái)使用FormCollection接收值4. 使用EF Code First搭建簡(jiǎn)易ASP.NET MVC網(wǎng)站并允許數(shù)據(jù)庫(kù)遷移5. ASP.NET MVC使用Identity增刪改查用戶6. ASP.NET MVC使用Quartz.NET執(zhí)行定時(shí)任務(wù)7. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條8. ASP.NET MVC視圖頁(yè)使用jQuery傳遞異步數(shù)據(jù)的幾種方式詳解9. ASP.NET MVC限制同一個(gè)IP地址單位時(shí)間間隔內(nèi)的請(qǐng)求次數(shù)10. log4net在Asp.net MVC4中的使用過(guò)程
