views:

44

answers:

2

I want to run some code from an ASP.NET MVC controller action in a new thread/asynchronously. I don't care about the response, I want to fire and forget and return the user a view while the async method runs in the background. I thought the BackgroundWorker class was appropriate for this?

public ActionResult MyAction()
{
    var backgroundWorker = new BackgroundWorker();
    backgroundWorker.DoWork += Foo;
    backgroundWorker.RunWorkerAsync();

    return View("Thankyou");
}

void Foo(object sender, DoWorkEventArgs e)
{
    Thread.Sleep(10000);
}

Why does this code cause there to be a 10 second delay before returning the View? Why isnt the View returned instantly?

More to the point, what do I need to do to make this work?

Thanks

+2  A: 

You can just start new thread:

public ActionResult MyAction()
{
    var workingThread = new Thread(Foo);
    workingThread.Start();

    return View("Thankyou");
}

void Foo()
{
    Thread.Sleep(10000);
}
bniwredyc
Cheers, just wondering why the background worked blocks though?
Andrew Bullock
You can see BackgroundWorker soucre code to find out. BackgroundWorker is WinForms component and I think it's not correct to use it in ASP.NET.
bniwredyc
+1  A: 

andrew,

wouldn't you be better using the Asynccontroller:

http://msdn.microsoft.com/en-us/library/ee728598.aspx

http://www.wintellect.com/CS/blogs/jprosise/archive/2010/03/29/asynchronous-controllers-in-asp-net-mvc-2.aspx

and then using async methods on that?? or have you explored this avenue without success??

jim
AsyncController would produce the same outcome. The idea of an Asynccontroller is to do a potentially long operation asynchronously (like send an email) while freeing up more ASP.NET worker threads to serve immediate requests. When the operation completes, the user is served the response page. The end result is that the user sees a particularly long request, even though the operation is happening on a background thread. The OP wants his background thread to execute, but the user doesn't have to wait for that thread to complete.
villecoder
gotcha... no worries.
jim
what @villecoder said ;)
Andrew Bullock
yup - i see that. as i said in the post, you may have explored that avenue without success. hope you get it figured.
jim