How can long running thread work inside web application

前端 未结 2 1444
别那么骄傲
别那么骄傲 2021-01-29 03:08

So I have inside MVC controller method the following code :

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

             


        
2条回答
  •  日久生厌
    2021-01-29 03:31

    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.

提交回复
热议问题