Janis Jansen
Janis Jansen

Reputation: 1025

C# does removing an object from a List clear event handlers

I have a .NET Core backend with SignalR that accepts client connections. On every connection a so called "scheduler" is created and stored in a Dictionary. Once a connection is closed this scheduler object is removed from the list.

Now, for these scheduler objects I set some CollectionChanged handlers for object properties like this:

...
scheduler.Grades.CollectionChanged += (s, e) => this.GradesListener(s, e, connectionId);
scheduler.Raws.CollectionChanged += (s, e) => this.MaterialsListener(s, e, connectionId);
scheduler.Heats.CollectionChanged += (s, e) => this.HeatsListener(s, e, connectionId);
...

Because there is a memory leak in the application my question is: If I remove the scheduler from the Dictionary (I do this with Dictionary.Remove(key)), are the event listeners removed as well? I would think so because the properties (Grades, Raws, Heats...) will be deleted as well, right?

If the handlers are not automatically removed, how would I "unregister" them?

Let me know if I need to provide more code.

I'm sorry if a question like this was asked before, I just couldn't find an answer.

Upvotes: 1

Views: 514

Answers (1)

Ygalbel
Ygalbel

Reputation: 5529

You right, After you remove entries from Grades, Raws and Heats, the GC will clean memory fine.

The problem is until you remove them this instance can't be cleaned.

You can find more information how to avoid memory leaks here.

Upvotes: 1

Related Questions