Running code after sending the http reponse to the client in ASP.NET

Let’s say you want to do a time consuming operation on the background
when a user hits a button on a webpage.

On the button click event add this code:

// A new thread is needed so the client does not have to 
// wait for the processing to be completed.
Thread t = new Thread(new ParameterizedThreadStart(TryToEmailAdmissionsRep));

Note that the code above calls the TryToEmailAdmissionsRep method. This
method takeas a parameter and that is why we’re doing using
ParameterizedThreadStart as opposed to just ThreadStart.

And there is one more trick that I know is needed when the website is running
from VS2008’s built in web server. I’m not sure if it’s needed on VS2010 or
when the website is running on IIS.

private void TryToEmailAdmissionsRep(object username)
    // This test line helps you see that the user
    // is really not waiting for the execution of this method.
    // Remove line after testing.

    // pliska: I added this try-catch because if an exception 
    // is thrown by this code, the line that threw the exception 
    // is executed over and over again throwing the exception 
    // over and over again in an infinite loop. This could be a
    // bug on the VS debugger but maybe it's actually happening
    // so I'm catching all exceptions.
        // This is where you would do the work. In this case
        // email the admissions representative.

    catch (Exception ex)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s