Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do i have to unsubscribe from events when closing a window in wpf?

Tags:

c#

wpf

the tiltle says it all, in my window (not the main window) constructor i have

EventAggregator.OnUserLoggedIn += OnUserLoggedIn;
EventAggregator.OnUserLoggedOff += OnUserLoggedOff;

is there a difference between

this.Close()

and

EventAggregator.OnUserLoggedIn -= OnUserLoggedIn;
EventAggregator.OnUserLoggedOff -= OnUserLoggedOff;
this.Close()

i've read that closing the window disposes all unmanged resources, are those events considered maneged or unmanaged?

like image 517
FPGA Avatar asked Dec 25 '22 18:12

FPGA


1 Answers

Those events are managed resources if anything (I'm not sure if you can call events resources though).

Yes, you should unhook event handlers from child windows (not main window as it doesn't matter) otherwise you may experience memory leaks as garbage collector won't be able to pick up those objects as still having references.

Check this blog for more info on memory leaks and event handlers:

A classic leak common to all .NET applications, and a common oversight by developers. If you create an event handler to handle events occurring in some other object then, if you don't clear the link when you've finished, an unwanted strong reference will be left behind.

like image 62
Szymon Avatar answered Feb 02 '23 01:02

Szymon