最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時間:2022年10月17日 09:58:09   作者:Darren?Ji  
這篇文章介紹了ASP.NET?MVC使用異步Action的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

在沒有使用異步Action之前,在Action內(nèi),比如有如下的寫法:

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

以上,假設(shè),GetCustomerData方法是調(diào)用第三方的服務(wù),整個過程都是同步的,大致是:

→請求來到Index這個Action
→ASP.NET從線程池中抓取一個線程
→執(zhí)行GetCustomerData方法調(diào)用第三方服務(wù),假設(shè)持續(xù)8秒鐘的時間,執(zhí)行完畢
→渲染Index視圖

在執(zhí)行執(zhí)行GetCustomerData方法的時候,由于是同步的,這時候無法再從線程池抓取其它線程,只能等到GetCustomerData方法執(zhí)行完畢。

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

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

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

假設(shè)有這樣的一個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)在就可以寫一個異步Action了。

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

Index視圖和同步的時候相比,并沒有什么區(qū)別。

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

當(dāng)然,異步還設(shè)計到一個操作超時,默認(rèn)的是45秒,但可以通過AsyncTimeout特性來設(shè)置。

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

如果不想對操作超時設(shè)限。

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

綜上,當(dāng)涉及到調(diào)用第三方服務(wù)的時候,就可以考慮使用異步Action。async和await是異步編程的2個關(guān)鍵字,async總和Action

到此這篇關(guān)于ASP.NET MVC使用異步Action的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論

鄯善县| 广元市| 菏泽市| 嘉鱼县| 兴山县| 石景山区| 塘沽区| 郧西县| 盈江县| 乐清市| 从江县| 江口县| 霍城县| 和政县| 炉霍县| 蒙自县| 天门市| 金寨县| 土默特右旗| 永康市| 中西区| 武陟县| 彰武县| 勐海县| 芦山县| 会同县| 和田县| 长岛县| 柯坪县| 青岛市| 伽师县| 乡宁县| 瓦房店市| 大新县| 曲水县| 望都县| 祁阳县| 凌云县| 镇坪县| 白玉县| 诸城市|