国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

ASP.NET MVC使用異步Action的方法

瀏覽:103日期:2022-06-08 16:04:00

在沒有使用異步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方法執行完畢。

這時候,可以改善一下整個過程。

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

所以,當涉及到多種請求,比如,一方面是來自客戶的請求,一方面需要請求第三方的服務或API,可以考慮使用異步Action。

假設有這樣的一個View Model:

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

假設使用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;				
	}
}

現在就可以寫一個異步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

到此這篇關于ASP.NET MVC使用異步Action的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持。

標簽: ASP.NET
相關文章:
主站蜘蛛池模板: 汉中市| 冕宁县| 湖口县| 岑巩县| 西安市| 平顶山市| 科技| 高雄市| 凯里市| 乐平市| 阳曲县| 新沂市| 韩城市| 磐石市| 大关县| 宁城县| 元朗区| 大安市| 平邑县| 湟中县| 静海县| 普陀区| 诸暨市| 樟树市| 周宁县| 稷山县| 浪卡子县| 古交市| 获嘉县| 南康市| 石屏县| 江华| 阿拉尔市| 富阳市| 宁陕县| 杭锦旗| 呼玛县| 平定县| 桐柏县| 夏邑县| 滁州市|