ASP.net global.asax 计时器随机停止工作

ASP.net global.asax Timers randomly stop working

给定代码:

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();
}

在看似随机的情况下,计时器会停止计时,除非我重新启动网站,否则不会再次启动。

它没有抛出任何异常,但查看 Windows 错误日志有一些条目:

  • 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.

站点处于活动状态(应用程序池的启动模式为AlwaysRunning

我明白,正是出于这个原因,以这种方式使用计时器并不是针对关键问题的推荐方法,但我无法解释为什么它会默默地、明显地随机地放弃。

根据您的代码,我希望垃圾收集器能够收集您的计时器,因为它没有句柄。你有没有试过类似

static Timer testTimer ;
protected void Application_Start(object sender, EventArgs e)
{
     testTimer = new Timer(...);
}
由于卸载 AppDomain 的方式、线程模型和许多其他因素,

ASP.NET 不适合 运行ning 计时器。

我建议您阅读 Scott Hanselman 的 this blog post,其中讨论了在 ASP.NET 网络应用程序中成功 运行 基于计时器的代码的各种方法。