1

I need a operations which needs to run every x seconds forever, and to achieve this I did:

protected void Application_Start()
{
    InitialieOnce.Initialize();
}

public static class InitialieOnce
{
    private static bool initialized = false;

    public static void Initialize()
    {
        if (initialized == false)
        {
            initialized = true;
            Thread t = new Thread(x => CheckStatus());
            t.IsBackground = true;
            t.Start();
        }
    }

    private static void CheckStatus()
    {
        //My script goes here.
        Thread.Sleep(8000);
        CheckStatus();
    }
}

After some time (about 5 minutes) I get this error:

"An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll"

Can this error be related to how I made my infinite loop?

If yes, is there a better way to achieve this, can I fix it, or is this code ok?

3 Answers 3

5

You are calling "CheckStatus" recursively. So every 8 seconds there will be one more entry on your call stack:

CheckStatus() -> CheckStatus() -> CheckStatus() -> and so on.. until you get a StackOverflowException.

Instead you should use

while (true)
{
    /* Your Code */
    Thread.Sleep(8000);
}

Please also note that by default IIS will unload your application if there was no request in 15 minutes, resulting in your thread being killed.

0
5

Consider creating a Windows service for such a thing, instead of abusing IIs..

I don't know where, but I read that IIs isn't good for creating long living services like in javas servers.

1
  • I'm going to hope for the best. Thank your for the warning.
    – BjarkeCK
    Dec 9, 2012 at 11:51
0

I would also suggest creating a Windows service for that, something like a daemon. You can create a service that will just call a special action on your application on regular intervals. The rest of the work will be done within your MVC application. Have a look at this post for an example.

2
  • This is an alternative that I have used and tested. Whatever implementation you choose, test it by making your method write a timestamp to a file or your database every time it is called and then let your application run for a long time without any requests.
    – Panos
    Dec 9, 2012 at 15:12
  • Ah okay i see. Yes the script will stop after 15 minutes or so, if the there's no activity on the site. but that is fine, as long as at it starts up again when the there's activity again. And it does.
    – BjarkeCK
    Dec 9, 2012 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.