13

User request some page at my website.

What i want to do? Send to user a fast answer and start background task which take a long time. It looks like:

public ActionResult index()
{
    var task = new Task(Stuff);

    //start task async
    task.start(); 

    return View();
}

public void Stuff()
{
    //long time operation    
}

How can i do it?

1
  • 4
    How can do what? You already have the code, what's wrong with it?
    – svick
    Mar 13, 2012 at 12:59

3 Answers 3

19

You can pass the Task StartNew() method a parameter that indicates the task you're starting is "long running", which provides a hint to the Task Scheduler to start the task on a new thread.

var task = Task.Factory.StartNew(Stuff, TaskCreationOptions.LongRunning);
4

Here's an example from MSDN http://msdn.microsoft.com/en-us/library/ms978607.aspx#diforwc-ap02_plag_howtomultithread

While you need it for ASP.NET MVC, you can use the core idea of this ASP.NET WebForms example.

The approach is create a worker thread to do your job, start it and send a "waiting" page to the user. This "waiting" page will refresh at every N seconds, looking for the results processed by the worker thread. When it finishes, the "waiting" page shows the results.

0

you want to define a delegate and fire it off before returning. See, for example: http://msdn.microsoft.com/en-us/magazine/cc301332.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.