Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is a background worker in a controller async?

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);
                        }

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?

like image 652
rksprst Avatar asked Aug 24 '10 22:08

rksprst


People also ask

What is async controller in MVC?

The asynchronous controller enables you to write asynchronous action methods. It allows you to perform long running operation(s) without making the running thread idle. It does not mean it will take lesser time to complete the action.

What is a background Worker?

The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running.

What is a background Worker in c#?

A BackgroundWorker component executes code in a separate dedicated secondary thread. In this article, I will demonstrate how to use the BackgroundWorker component to execute a time-consuming process while the main thread is still available to the user interface.


1 Answers

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();
}

More info on the AsyncController here: MVC AsyncController

like image 138
Steve Michelotti Avatar answered Nov 15 '22 04:11

Steve Michelotti