0

I have a loop that is supposed to run for 120 minutes, but it always stops suddenly after about 20 minutes.

My code:

var sw = new Stopwatch();
sw.Start();
int tineout = 120 * 60000;
while (sw.ElapsedMilliseconds < tineout)
{
}
w.Stop();
return;
ad absurdum
  • 19,498
  • 5
  • 37
  • 60
  • 2
    What are you trying to do, and why? Having a web app hang a response for two hours seems a little odd. – Flydog57 Feb 01 '21 at 05:35
  • What's the point of this code? The only thing it does is make a CPU core unusable and effectively burn money (as CPU cost in the cloud, as power/cooling in the datacenter, and requiring an extra core to take up the load in both cases). IIS prevents this for happening by recycling threads, which is a VERY GOOD thing. If you wanted to wait for 20 or 120 minutes you could have used a timer, although in a web application that would require some careful coding – Panagiotis Kanavos Feb 01 '21 at 08:09
  • 2
    What is the actual problem you want to solve? Whatever it is, there are proper ways to do it. For running background tasks [there are options from QueueBackgroundWorkItem to HangFire](https://www.hanselman.com/blog/how-to-run-background-tasks-in-aspnet) and in ASP.NET Core, [Background Services](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-5.0&tabs=visual-studio). There are ways to warm up a web app, even on a schedule, and ways to prevent recycling including ..... just increasing the recycle timeout. – Panagiotis Kanavos Feb 01 '21 at 08:16

1 Answers1

3

IIS will kill your app pool thread after 20 minutes of idle time by default, to save resources. If you keep getting requests, the thread will stay alive. In this case, "idle" means no new HTTP requests, so even though you're still doing work, it's still idle from the perspective of this timeout.

You can change this; 20 minutes is just a default. Or you can set up monitoring for the site using a free service like UpTime Robot to send (and report!) periodic requests and therefore keep the App Pool from going idle. You should be doing that anyway.

But probably you're better off thinking of a different way to do whatever long-running task this is.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794