本文介绍了在控制器的异步后台工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个asp.net MVC 2的控制器,我有以下的code:

Inside an asp.net mvc 2 controller, I have the following code:

using (BackgroundWorker worker = new BackgroundWorker())
                        {
                            worker.DoWork += new DoWorkEventHandler(blah);
                            worker.RunWorkerAsync(var);
                        }

我的问题是:这是code异步,这意味着它启动一个新的线程,而'嗒嗒'并行正在执行控制器返回视图

My question is: is this code async, meaning it launches a new thread and the controller returns the view while 'blah' is executing in parallel?

如果不是,我将如何实现这些结果?

If not, how would I achieve these results?

推荐答案

在MVC 2有一个新的功能,叫做AsyncController这是做MVC异步调用的正确方法。您的控制器应AsyncController而不是继承的控制器。然后,你的主要操作方法的名字应该有异步的结束。例如,如果您有名为布拉赫()的操作方法,你BlahAsync名()来代替,而这将由框架自动识别(并使用BlahCompleted()回调):

In MVC 2 there is a new feature called the AsyncController which is the correct way to do async calls in MVC. Your controller should inherit from AsyncController rather than controller. Then you your primary action method name should have "Async" on the end. for example, if you had an action method called Blah(), you name in BlahAsync() instead and this will be automatically recognized by the framework (and use BlahCompleted() for the callback):

public virtual void BlahAsync()
{
    AsyncManager.OutstandingOperations.Increment();
    var service = new SomeWebService();
    service.GetBlahCompleted += (sender, e) =>
        {
            AsyncManager.Parameters["blahs"] = e.Result;
            AsyncManager.OutstandingOperations.Decrement();
        };
    service.GetBlahAsync();
}

public virtual ActionResult BlahCompleted(Blah[] blahs)
{
    this.ViewData.Model = blahs;
    return this.View();
}

在AsyncController此处了解详情:

这篇关于在控制器的异步后台工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 08:51