Tom Gullen
Tom Gullen

Reputation: 61729

ASP.net global.asax Timers randomly stop working

Given the code:

protected void Application_Start(object sender, EventArgs e)
{
    var testTimer = new Timer(
        LogTimer,
        null,
        new TimeSpan(0, 0, 0, 0),
        new TimeSpan(0, 0, 0, 1)
    );
}

public static void LogTimer(object sender)
{
    "Hello".Log();
}

At seemingly random occasions the timer stops firing, and wont start again unless I restart the website.

It doesn't throw any exceptions, but looking in the Windows error log there are some entries:

  • The Open Procedure for service "Lsa" in DLL "C:\Windows\System32\Secur32.dll" failed. Performance data for this service will not be available. The first four bytes (DWORD) of the Data section contains the error code.

  • Unable to open the Server service performance object. The first four bytes (DWORD) of the Data section contains the status code.

The site is active (the start mode of the app pool is AlwaysRunning.

I understand that using timers in this way is not a recommended approach for critical things for exactly this reason, but I am failing to come up with an explanation as to why it's silently and apparently randomly just giving up.

Upvotes: 0

Views: 739

Answers (2)

Martin Costello
Martin Costello

Reputation: 10843

ASP.NET isn't suited to running timers due to the way AppDomains get unloaded, the threading model and many other factors.

I suggest you read this blog post from Scott Hanselman that discusses various ways to successfully run timer-based code in ASP.NET web applications.

Upvotes: -1

Ashkan S
Ashkan S

Reputation: 11471

From your code, I expect the garbage collector to collect your timer since there is no handle for that. have you tried something like

static Timer testTimer ;
protected void Application_Start(object sender, EventArgs e)
{
     testTimer = new Timer(...);
}

Upvotes: 3

Related Questions