ASP.NET MVC使用異步Action的方法
在沒有使用異步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è)過程都是同步的,大致是:
→請求來到Index這個(gè)Action
→ASP.NET從線程池中抓取一個(gè)線程
→執(zhí)行GetCustomerData方法調(diào)用第三方服務(wù),假設(shè)持續(xù)8秒鐘的時(shí)間,執(zhí)行完畢
→渲染Index視圖
在執(zhí)行執(zhí)行GetCustomerData方法的時(shí)候,由于是同步的,這時(shí)候無法再從線程池抓取其它線程,只能等到GetCustomerData方法執(zhí)行完畢。
這時(shí)候,可以改善一下整個(gè)過程。
→請求來到Index這個(gè)Action
→ASP.NET從線程池中抓取一個(gè)線程服務(wù)于Index這個(gè)Action方法
→同時(shí),ASP.NET又從線程池中抓取一個(gè)線程服務(wù)于GetCustomerData方法
→渲染Index視圖,同時(shí)獲取GetCustomerData方法返回的數(shù)據(jù)
所以,當(dā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í)候相比,并沒有什么區(qū)別。
@model List<Customer>
@foreach(var customer in Model)
{
<span>@customer.Name</span>
}
當(dāng)然,異步還設(shè)計(jì)到一個(gè)操作超時(shí),默認(rèn)的是45秒,但可以通過AsyncTimeout特性來設(shè)置。
[AsyncTimeout(3000)]
public async Task<ActionResult> Index()
{
...
}
如果不想對操作超時(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的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持。
相關(guān)文章:
1. ASP.NET MVC實(shí)現(xiàn)下拉框多選2. ASP.Net MVC利用NPOI導(dǎo)入導(dǎo)出Excel的示例代碼3. ASP.NET MVC實(shí)現(xiàn)單個(gè)圖片上傳、限制圖片格式與大小并在服務(wù)端裁剪圖片4. ASP.NET MVC擴(kuò)展帶驗(yàn)證的單選按鈕5. ASP.NET MVC實(shí)現(xiàn)樹形導(dǎo)航菜單6. ASP.NET MVC實(shí)現(xiàn)城市或車型三級聯(lián)動7. ASP.NET MVC使用Session會話保持表單狀態(tài)8. ASP.NET MVC實(shí)現(xiàn)橫向展示購物車9. ASP.NET MVC使用JSAjaxFileUploader插件實(shí)現(xiàn)單文件上傳10. log4net在Asp.net MVC4中的使用過程

網(wǎng)公網(wǎng)安備