JG in SD
JG in SD

Reputation: 5607

What happens to running tasks when IIS recycles

To help with performance of the clients, I offload the processing of a request onto a task. This is done because the processing usually takes a bit of time, and I don't want the clients to be waiting for a while just to get the 200 response. The web service that offloads the work onto a task is always processing posts.

public void ProcessRequest(HttpContext context)
{
    // check for bad requests -- return 400

    // get copy of the context input stream

    Task.Factory.StartNew(() =>
    {
        ProcessRequest(contextInputStreamCopy);
    });
}

private void ProcessRequest(Stream inputStream)
{
    try
    {
        // process input stream
    }
    catch(Exception ex)
    {
        // any server error that would normally result in 500 response are not
        // exposed to the clients, the clients are to see 200 when the server 
        // encounters an error
    }
}

So my question is what happens to these tasks when IIS recycles, or when the web site is being stopped.

Upvotes: 5

Views: 2996

Answers (2)

Aristos
Aristos

Reputation: 66641

When IIS recycles, it waits for all that threads to finish and exits - up to the timeout value that have on pool. After that time out they kills all running threads and start again.

So you may set a signaling to your threads to stop when the application request to shut down at globa.asax using the Application_End functions.

Upvotes: 8

cuongle
cuongle

Reputation: 75306

What happens to running tasks when IIS recycles

It simply takes your running task down accordingly when IIS recycles. If your task takes a bit time, you should think to run your task on separate process. A corrective approach is to use Queue (MSMQ, RabbitMQ...) to store your tasks and use another process to pick your tasks from queue to run. You can use Windows Service or Console Host with scheduler for this.

More information from Phil Haack:

When ASP.NET tears down the AppDomain, it will attempt to flush the existing requests and give them time to complete before it takes down the App Domain. ASP.NET and IIS are considerate to code that they know is running, such as code that runs as part of a request.

Problem is, ASP.NET doesn’t know about work done on a background thread spawned using a timer or similar mechanism. It only knows about work associated with a request.

Upvotes: 6

Related Questions