Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eventhandlers and application lifetime objects in c# - should I unhook?

Say I've got an object that exists for the duration of an application. Let's call it GlobalWorker. GlobalWorker has events e.g. UserLoggedIn to which other objects can subscribe. Now imagine I've got a Silverlight page or an asp.net page or something, that subscribes to the UserLoggedIn event when it is constructed.

public SomePage()
{
GlobalWorker.Instance.UserLoggedIn += new EventHandler(OnUserLoggedIn);
}

private void OnLoggedIn(object sender, EventArgs e)
{

}

Does the existence of this event prevent the page from being garbage collected? If so, what's the best pattern to use in this instance: weak event-handlers, move the subscription to the Load event and unsubscribe in the UnLoad event?

like image 703
Stephen Ellis Avatar asked Nov 22 '10 18:11

Stephen Ellis


1 Answers

Use Weak Events.

This is a common problem in WPF and it is good you have thought about it.

like image 107
Aliostad Avatar answered Sep 30 '22 03:09

Aliostad