sino
sino

Reputation: 766

How can long running thread work inside web application

So I have inside MVC controller method the following code :

public ActionResult ProcessFile () 
{
    ThreadStart threadStart = new ThreadStart ( ()=>{

        // Doing some long processing that takes 20 minute 
    } );

    Thread thread = new Thread(threadStart); 
    thread.Start();
}

The problem here is that when more than one request sent to this controller method the thread get killed. I need to Thread to stay working untill the processing ends , and it seem it is a matter of resources the much resources get taken the less threads can stay working . If I run the process from windows application or service it works perfectly , it is only having problem when it get started from web application .

Upvotes: 1

Views: 5168

Answers (2)

SalieHendricks
SalieHendricks

Reputation: 61

While the answer above is acceptable, there is some merit to having long running service like tasks hosted in your web app.

Rick Strahl has a blog post about it here: Use-IIS-Application-Initialization-for-keeping-ASPNET-Apps-alive

Upvotes: 0

danielfishr
danielfishr

Reputation: 879

Ideally you should not create threads (for long running background jobs) off web requests in IIS 7.

The threads will be stopped should the app pool/AppDomain restart, which could happen for a number of reasons such as changes to the contents of the bin folder, changes to web.config, a period of inactivity, a resource threshold is reached (e.g. memory usage). In fact the AppDomain will restart periodically by default for no other reason than it has been alive for x amount of time.

For this reason long running tasks should be implemented using a job queue and background job runner, e.g. console app or windows service (importantly, not running in the context of IIS), processing those jobs.

The web request should simply add the job to the queue allowing the background job runner to pick up the jobs as they appear.

A similar question has been answered here Can I use threads to carry out long-running jobs on IIS?

Edit: A seriously not recommended alternative

If you insist or have no alternative but to run the background job in the IIS process, you need to look at allowing the background job to be spontaneously stopped, and allowing it to restart from where it left off when it was stopped.

You can have a URL which can be polled to trigger the restart of unfinished jobs.

I have seen this work in the past, the implementation will vary in complexity based on what the background job entails.

You will find the server may begin to have performance issues as background jobs are started and killed repeatedly.

Upvotes: 6

Related Questions