I read about memory management and came across a situation in a project where a book or Google came up with the exact answer. I already know that delegates manage objects, and events control instances of a delegate. Having said that, delegate instances will be deleted from memory after the application terminates.
I cannot figure out how to ensure that the external code releases all event references until the moment my class is deleted (explicitly or GC). As an example, class A provides an event, and class B consumes it. Class B calls Dispose on class A without releasing delegate references. Of course, we cannot throw an error from the Dispose method itself.
Below is a class with a delegate and another that uses it.
public class ClassB { private ClassA A { get; set; } public ClassB() { this.A = new ClassA(); this.A.OnProcessed += new ClassA.DelegateProcessed(this.ClassA_Processed); } public void Process() { this.A.Process(); } public void ClassA_Processed (ClassA sender, EventArgs e) {
We need to make sure that ClassA is suitable for garbage collection no matter what the developer does with ClassB. The bottom line is to minimize the amount of time that ClassA spends in memory, even if the consumer is sloppy.
UPDATE . From the responses it is clear that the events should not be explicitly deleted from ClassA. Regarding the main issue, the methods seem to be weak recommendations, as shown below. The goal is to minimize the time that ClassA remains in memory. Please let me know in case I missed any of them.
source share