網站首頁 編程語言 正文
在沒有使用異步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
原文鏈接:https://www.cnblogs.com/darrenji/p/4436764.html
相關推薦
- 2022-12-13 Python按天實現生成時間范圍序列的方法詳解_python
- 2022-11-10 pytorch算子torch.arange在CPU?GPU?NPU中支持數據類型格式_python
- 2022-09-03 Matplotlib中文亂碼的兩種詳細解決方案_python
- 2022-10-08 淺談數據庫日期類型字段設計應該如何選擇_MsSql
- 2022-07-02 python等間距取值方式_python
- 2022-07-17 關于python通過新建環境安裝tfx的問題_python
- 2023-01-13 Qt中QList與QLinkedList類的常用方法總結_C 語言
- 2022-03-24 聊一聊redis奇葩數據類型與集群知識_Redis
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支