CLR via C# 读书笔记 22 编译器优化导致的问题 Timer

DotNet项目在Debug 和Release 模式一个主要的差别就是有没有打开编译器优化

在Release下由于采用了编辑器优化,那么原来有些运行正常的代码就会出问题

下列代码, 系统觉得Timer已经没有用了...所以就被回收了..

所以在Release模式下 timer只会执行一次

(注意如果是Debug模式那么一直运行)

(注意如果使用Visual Studio的调试器, vs会帮你延长临时变量的生命周期...那么也会一直运行)

(调用GC.Collect()是为了显式执行GC 以体现t被回收的情况, 真实情况中 非常不推荐显式的调用GC.Collect() )

代码
using System;
using System.Threading;
public static class Program
{
public static void Main()
{
// Create a Timer object that knows to call our TimerCallback
// method once every 2000 milliseconds.
Timer t = new Timer(TimerCallback, null, 0, 2000);
// Wait for the user to hit <Enter>
Console.ReadLine();
}
private static void TimerCallback(Object o)
{
// Display the date/time when this method got called.
Console.WriteLine("In TimerCallback: " + DateTime.Now);
// Force a garbage collection to occur for this demo.
GC.Collect();
}
}

修复此类问题一般是把临时变量提升到类的成员变量

例如 private static Timer t; (不可能被gc)

还有 private Timer t ; (如果当前类的实例还在 就不会被gc)

原文地址:https://www.cnblogs.com/PurpleTide/p/1886581.html