为什么Timer运行一段时间自动停止

.Net技术 码拜 8年前 (2016-02-24) 1979次浏览
做了一个服务,需要5分钟执行一次,但是只执行了4次(每隔5分钟),日志就没有了。问一下这是怎么回事呢?
试了好几次,有时候是只运行5次,总之运行一段时间Timer就会停止,而查看服务本身还在运行

protected override void OnStart(string[] args)
 {
            log.Info("服务启动...");          
            try
            {
                Thread t1 = new Thread(new ThreadStart(RunThread));
                t1.Start();
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
 }
public void RunThread()
 { 
            //立即执行定时器,每隔5分钟执行一次
            System.Threading.Timer t = new System.Threading.Timer(new TimerCallback(GetTsLocation), null,0, 1000 * 60 * 5);      
 }
public void GetTsLocation(object obj)
 {
            log.Info("正在运行..");
}

下面是日志

Date:2016-07-02 17:58:49,194
thread:6
Level:INFO
Class:TgldHcwcService.ServiceTgld
File:
Line:0
Message:服务启动...
Date:2016-07-02 17:58:49,319
thread:7
Level:INFO
Class:TgldHcwcService.ServiceTgld
File:
Line:0
Message:正在运行..
Date:2016-07-02 18:03:49,308
thread:13
Level:INFO
Class:TgldHcwcService.ServiceTgld
File:
Line:0
Message:正在运行..
Date:2016-07-02 18:08:49,312
thread:27
Level:INFO
Class:TgldHcwcService.ServiceTgld
File:
Line:0
Message:正在运行..
Date:2016-07-02 18:13:49,316
thread:37
Level:INFO
Class:TgldHcwcService.ServiceTgld
File:
Line:0
Message:正在运行..
解决方案

10

至少,你要把变量 t 声明在方法外边。
假如 log.Info(“正在运行..”) 执行之前恰好进行了一次比较深度的内存清理,那么你的 Timer 对象就销毁了。

10

同意sp1234的观点,把t作为成员变量看看。

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明为什么Timer运行一段时间自动停止
喜欢 (0)
[1034331897@qq.com]
分享 (0)