Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backgroundworker blocking MVC controller action

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

like image 216
Andrew Bullock Avatar asked Oct 05 '10 11:10

Andrew Bullock


1 Answers

You can just start new thread:

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

    return View("Thankyou");
}

void Foo()
{
    Thread.Sleep(10000);
}
like image 130
bniwredyc Avatar answered Sep 22 '22 04:09

bniwredyc