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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With