Объект не освобождается без привязки к таймеру
public class Program { public static void Main(string[] args) { object obj = new ObjectWithTimer(); Console.ReadLine(); Console.WriteLine("obj=null"); obj = null; Console.ReadLine(); } } public class ObjectWithTimer { private int i; public System.Timers.Timer t; public ObjectWithTimer() { t = new System.Timers.Timer(5000); t.Elapsed += Obj_Elapsed; t.Enabled = true; } public void Obj_Elapsed(object sender, ElapsedEventArgs e) { i++; Console.WriteLine(i); } }
Что я уже пробовал:
Hi all, Please see example below. Even though the reference to obj is set to null, the obj is not released and Obj_Elapsed continues printing i. Notice there is no reference to the timer out of the scope of the ObjectWithTimer constructor.