準備工作
- 引用
Microsoft.Web.Mvc.dll (Futures 程序集)
- 路由註冊改用
MapAsyncRoute
- Controller 繼承
AsyncController
// Global.asax
routes.MapAsyncRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
// Controller
public class HomeController : AsyncController { }
模式一:Action / ActionCompleted 配對
// 請求 /Home/Async1
public void Async1() {
AsyncManager.OutstandingOperations.Increment();
Task.Run(() => {
// 異步邏輯
var data = _repo.GetData();
AsyncManager.Parameters["data"] = data;
AsyncManager.OutstandingOperations.Decrement();
});
}
public ActionResult Async1Completed() {
var data = AsyncManager.Parameters["data"] as MyData;
return View(data); // 或 Json(data), Content(...)
}
模式二:Action / ActionCompleted 帶參數
public void Async2(int id) {
AsyncManager.OutstandingOperations.Increment();
_service.BeginGetDetail(id, ar => {
var result = _service.EndGetDetail(ar);
AsyncManager.Parameters["detail"] = result;
AsyncManager.OutstandingOperations.Decrement();
}, null);
}
public ActionResult Async2Completed(DetailModel detail) {
// 參數自動從 AsyncManager.Parameters 綁定
return View(detail);
}
模式三:委托模式
[AsyncTimeout(5000)] // 超時屬性
[NoAsyncTimeout] // 禁用超時
public ActionResult Async3() {
return AsyncManager.Async(() => {
return _service.GetReport(); // 返回 ActionResult
});
}
關鍵類型速查
| 類型 | 用途 |
AsyncController | 異步控制器基類 |
AsyncManager | 異步狀態管理、參數傳遞、超時控制 |
AsyncActionInvoker | 異步 Action 調度器 |
AsyncTimeoutAttribute | Action 級超時設置 |
MapAsyncRoute | 路由擴展方法 |
避坑指南
- 必須成對實現
Action + ActionCompleted,否則 404
AsyncManager.Parameters 僅在單次請求內有效,勿跨請求存儲
- 異常處理:在
Completed 中 try-catch,或重寫 OnException
- Session 訪問:異步線程中無
HttpContext,需主線程預取