在后台运行异步操作方法

cry*_*yss 5 c# asp.net-mvc asynchronous asp.net-mvc-4

有没有办法在标准操作方法中调用异步操作方法而不是等待异步方法执行(保持相同的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
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试使用Task类来执行backround工作,但是当我启动任务并且action方法返回了View时,请求被杀死并且我的DependencyResolver实例被删除,因此后台任务开始抛出异常.

第一个想法是执行Standard.Save(不调用后台任务)并返回View,其中可以在ajax中调用Background.Save方法.换句话说:将另一个请求调用到异步控制器,以启动后台任务.

主要问题是如何调用异步方法保留授权信息(在cookie中)和依赖解析器(在我的例子中:autofac).

Mar*_*uth -1

对我来说这非常有效:

    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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

该页面被发回,大约 10 秒后,异步出现在我的调试输出中。不确定这如何与 Cookie/身份验证信息一起使用,但怀疑您是否可以将值传递给该方法。

希望能帮助到你。