System.Threading.Timer定时器停止运行(失效)问题解决方法

一、现象

在一个WebAPI项目中某个方法Tools()里使用定时器

var timer = new System.Threading.Timer((unused) =>
            {
                Console.WriteLine("1");
            }, null, 0, 1000);//1秒一次

部署到IIS后,发现定时器老是失效,没有正确一秒执行一次。


二、探究

初步认为是timer为局部变量,在一个方法的生命周期结束后timer被回收了

于是将timer改成类成员变量,并写成静态变量

static System.Threading.Timer timer = null;

发现依然有问题,后来发现该方法是在

WebApiConfig.cs中的Register方法中new的类,这个类随着这个方法的结束,有可能被资源回收!

原来代码是:

public static class WebApiConfig
{
        public static void Register(HttpConfiguration config)
        {
		var tool = new Tools();
		tool.Run();
	}
}

改后代码

public static class WebApiConfig
{
	static Tools tool = new Tools();
        public static void Register(HttpConfiguration config)
        {	
		tool.Run();
	}
}

至此定时器正常运行。


你可能感兴趣的:(Asp.Net,.Net,Web,Api,C#)