2015-09-05 132 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

相关问题