从Asp.net MVC中的Custom Controller Factory调用Async方法

时间:2019-01-04 21:29:59

标签: c# asp.net-mvc

我正在使用自定义控制器工厂(通过扩展DefaultControllerFactory)并调用自定义ActionInvoker(重写InvokeAction方法)。现在,我需要从此自定义ActionInvoker方法调用Async方法。

问题不存在相应的Async InvokeAction方法,我可以重写该方法并用来从中调用Async方法。如果您有任何建议或建议从InvokeAction方法调用Async方法,请告诉我。

下面的代码示例使事情变得清晰。

public class CustomControllerFactory : DefaultControllerFactory
{
    // Assign custom Action Invoker
    controller.ActionInvoker = new CustomActionInvoker();     
}

public class CustomActionInvoker: ControllerActionInvoker
{
    public override bool InvokeAction(ControllerContext controllerContext, 
        string actionName)
    {
        // can not use await here since InvokeAction method can not be marked Async
        var result =  await GetView()
        base.InvokeActionResult(controllerContext, view);
        Return true;
    }
}

更新:

我可以从同步方法(InvokeAction)调用我的Async GetView方法吗?我的GetView()异步方法基本上是从外部源下载文件(网络操作)。我想我可以将Task.Run中的GetView()调用包装起来,这样我的主Asp线程将可用于处理其他一些Web请求。 Task.Run将仅从Asp线程池中获取线程吗?如果是的话,那么我想这并没有真正的优势,因为无论如何我都要消耗Asp线程池。

1 个答案:

答案 0 :(得分:-1)

您需要以这种方式使用异步行为

    protected override IAsyncResult BeginInvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor,
        IDictionary<string, object> parameters, AsyncCallback callback, object state)
    {

        // Initiate the asychronous call.
        var asyncResult = yourMethod.BeginInvoke(<your params>);

        // Wait for the WaitHandle to become signaled.
        asyncResult.AsyncWaitHandle.WaitOne();

        // Perform additional processing here.
        // Call EndInvoke to retrieve the results.
        var returnObject = yourMethod.EndInvoke(asyncResult);

        asyncResult.AsyncWaitHandle.Close();


        return base.BeginInvokeActionMethod(controllerContext, actionDescriptor, parameters, callback, state);
    }
相关问题