Foreword I know how to solve a problem. I want to know why . Please read the question from top to bottom.
As we all (should) know, adding event handlers can cause a memory leak in C #. See Why and How to Avoid Event Handler Memory Leaks?
On the other hand, objects often have similar or related life cycles, and deregistration from event loggers is optional. Consider this example:
using System; public class A { private readonly B b; public A(B b) { this.b = b; b.BEvent += b_BEvent; } private void b_BEvent(object sender, EventArgs e) {
A and B refer to each other implicitly through events, but GC can delete them (because it does not use reference counting, but mark-and-sweep).
But now consider this example:
using System; using System.Timers; public class C { private readonly Timer timer; public C() { timer = new Timer(1000); timer.Elapsed += timer_Elapsed; timer.Start();
Why doesn't the GC delete the C object? Why does the timer keep the object alive? Is the timer saved by some kind of "hidden" link of the timer mechanics (for example, by a static link)?
(*) Note: if the timer is created, it does not start, the problem does not occur. If it was started and later stopped, but the event handler was not canceled, the problem persists.
source share