首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET MVC Futures 異步 Action 官方實現使用指南

     編輯:關於ASP.NET

準備工作

  1. 引用 Microsoft.Web.Mvc.dll (Futures 程序集)
  2. 路由註冊改用 MapAsyncRoute
  3. 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 調度器
AsyncTimeoutAttributeAction 級超時設置
MapAsyncRoute路由擴展方法

避坑指南

  • 必須成對實現 Action + ActionCompleted,否則 404
  • AsyncManager.Parameters 僅在單次請求內有效,勿跨請求存儲
  • 異常處理:在 Completed 中 try-catch,或重寫 OnException
  • Session 訪問:異步線程中無 HttpContext,需主線程預取
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved