1

During an ASP.NET web request I need to kick off an asynchronous task and then return control back to the web page. Can someone show me the code for calling the below method? Just to be clear, I want the function called async and the web request to complete returning control to the calling page while the function is still processing.

private void FunctionToCall(IInterface objectIWantToPassIn)
{
   // do stuff
}
5
  • What version of C# are you using? Commented Apr 5, 2013 at 0:16
  • Sorry, 4.5. Should have mentioned that. Commented Apr 5, 2013 at 0:28
  • "Async" as in the async keyword, or "async" as in new thread? Commented Apr 5, 2013 at 0:33
  • async as in a new thread, but if the solution uses the new async keyboard, that would be fine. My needs are simple. I just want to kick off a new thread. I don't care if it throws an exception (presumably it will just die), I don't care when it ends (but I know it will never take more than a few seconds), and I don't need to resync with the caller. I want the calling web request to continue and finish while FunctionToCall runs on another thread. Commented Apr 5, 2013 at 0:39
  • 1
    There are so many ways to do this! This will also work: ((Action<IInterface>)FunctionToCall).BeginInvoke(objectIWantToPassIn, null, null); Commented Apr 5, 2013 at 5:47

2 Answers 2

2

You'll want to spawn the thread by creating a

Task task = Task.Factory.StartNew(action, "arg");

then you'll want to do something maybe when the task is done:

task.ContinueWith(anotheraction);

Of course action and otheraction would be void methods in this case.

Sign up to request clarification or add additional context in comments.

1 Comment

Both answers are correct and appreciated. However, this one uses the new TPL which is now preferred by the MS CLR team. blogs.msdn.com/b/pfxteam/archive/2009/10/06/9903475.aspx
1
 private void FunctionToCall(object state)
 {
        IInterface objectIWantToPassIn= (IInterface ) state;
        // do stuff
 }

  System.Threading.ThreadPool.QueueUserWorkItem(FunctionToCall, 
                                                objectIWantToPassIn);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.