简体   繁体   English

在后台运行异步操作方法

[英]Run async action method in background

Is there any way to call async action method in standard action method and not wait for the async method execution (keeping the same Request object)? 有没有办法在标准操作方法中调用异步操作方法而不是等待异步方法执行(保持相同的Request对象)?

public class StandardController : Controller
{
    public ActionResult Save()
    {
        // call Background.Save, do not wait for it and go to the next line

        return View();
    }
}

public class BackgroundController : AsyncController
{
    public void SaveAsync()
    {
        // background work
    }
}

I've tried to use Task class to do the backround work, but when I was starting the task and the action method has returned the View, the Request was killed and my DependencyResolver instance was erased, so the background task started to throw exceptions. 我已经尝试使用Task类来执行backround工作,但是当我启动任务并且action方法返回了View时,请求被杀死并且我的DependencyResolver实例被删除,因此后台任务开始抛出异常。

The first idea was to execute the Standard.Save (without calling the background task) and return the View in which the Background.Save method could be called in ajax. 第一个想法是执行Standard.Save(不调用后台任务)并返回View,其中可以在ajax中调用Background.Save方法。 So in other words: call the another request to the async controller, to start the background task. 换句话说:将另一个请求调用到异步控制器,以启动后台任务。

The main problem is how to call the async method keeping the authorization information (in cookies) and dependency resolver (in my case: autofac). 主要问题是如何调用异步方法保留授权信息(在cookie中)和依赖解析器(在我的例子中:autofac)。

You can run some async method in sync code: 您可以在同步代码中运行一些异步方法:

public class StandardController : Controller
{
    public ActionResult Save()
    {
        //code...
        YourMethod();
        //code...
        return View();
    }
    public async void YourMethod()
    {
      await Task.Run(()=>{
      //your async code...
      });
    }
}

YourMethod() will be going before and after Save() is fully performed. YourMethod()将在完全执行Save()之前和之后进行。

For me this is working great: 对我来说这很有用:

    public class PartnerController : Controller
    {
    public ActionResult Registration()
    {
        var model = new PartnerAdditional();
        model.ValidFrom = DateTime.Today;
        new Action<System.Web.HttpRequestBase>(MyAsync).BeginInvoke(this.HttpContext.Request, null, null);
        return View(model);
    }

    private void MyAsync(System.Web.HttpRequestBase req)
    {
        System.Threading.Thread.Sleep(5000);
        foreach (var item in req.Cookies)
        {
            System.Diagnostics.Debug.WriteLine(item);
        }
    }
}

The Page is posted back and aroud 10 seconds later Async appears in my Debug Output. 页面被回发并在10秒后发出异步,Async出现在我的调试输出中。 Not sure how this would work with Cookies/Authentication infos but in doubt you can pass the values to the method. 不确定这将如何与Cookies /身份验证信息一起使用,但有疑问您可以将值传递给方法。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM