2015-09-05 129 views
2

我想封裝在我的應用程序的一些功能,例如而不是每一個崗位的操作方法編寫這些代碼:使用擴展方法和自定義的ActionResult可以在自定義ActionResult中使用void異步方法嗎?

var baseUrl = context.HttpContext.Request.Url.Scheme + "://" + context.HttpContext.Request.Url.Authority + 
context.HttpContext.Request.ApplicationPath.TrimEnd('/') + "/signalr"; 
var hubConnection = new HubConnection(baseUrl); 
var notification = hubConnection.CreateHubProxy(hubName: HubName); 
await hubConnection.Start(); 
await notification.Invoke(MethodName); 
return RedirectToAction("TicketList", "Ticket") 

我做了這樣的事情:

return RedirectToAction("TicketList", "Ticket").WithSendNotification("notificationHub", "sendNotification"); 

爲了做到這一點我創建了一個自定義操作的結果,我把邏輯裏面ExecuteResult方法:

public async override void ExecuteResult(ControllerContext context) 
{ 
    var baseUrl = context.HttpContext.Request.Url.Scheme + "://" + context.HttpContext.Request.Url.Authority + 
    context.HttpContext.Request.ApplicationPath.TrimEnd('/') + "/signalr"; 
    var hubConnection = new HubConnection(baseUrl); 
    var notification = hubConnection.CreateHubProxy(hubName: HubName); 
    await hubConnection.Start(); 
    await notification.Invoke(MethodName); 
    InnerResult.ExecuteResult(context); 
} 

但我得到以下錯誤:

An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>. This exception may also indicate an attempt to call an "async void" method, which is generally unsupported within ASP.NET request processing. Instead, the asynchronous method should return a Task, and the caller should await it.

現在我的問題是,能否void async方法中的自定義操作的結果可以用嗎?

更新:ASP.NET 5有此能力,意思是除ActionResult.ExecuteResult之外的動作結果現在有ActionResult.ExecuteResultAsync。現在我想知道我們如何在MVC 5.0中實現這個功能?

+1

不是很清楚你爲什麼不想在控制器中重構方法......但是這裏有很長的問題和答案,爲什麼你真的不應該這樣做(包括像你一樣做火和忘記/崩潰的方式試圖做) - http://stackoverflow.com/questions/17659603/async-void-asp-net-and-count-of-outstanding-operations –

回答

1

由於Stephen表示,我不能在裏使用async在MVC 5.0中的能力。因爲我的目標是一點點的重構,我不得不使用ContinueWith

public override void ExecuteResult(ControllerContext context) 
{ 
    //.... 
    hubConnection.Start().ContinueWith(task => 
    { 
     if (task.IsCompleted) 
     { 
      notification.Invoke(MethodName); 
     } 
    }); 
    InnerResult.ExecuteResult(context); 
} 

現在,它就像一個魅力。

1

How can we implement this ability in MVC 5.0?

你不能。

正如您注意到的那樣,ASP.NET vNext將從頭開始重寫async。當前版本的ASP.NET(特別是MVC)有一些粗糙的優勢,它根本不可能使用async

相關問題