Eventhandlers and application lifetime objects in c#

Say I've got an object that exists for the duration of an application. Let's call it GlobalWorker. GlobalWorker has events eg 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?


Use Weak Events.

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


Yes the behavior prevents the page from being GC.

The reason being is that UserLoggedIn will hold a reference to SomePage indefinitely. There is no explicit removal of the handler and since weak events are not being used it will not implicitly get removed either.

You can use weak events as another poster stated, you can also re-think your design to some degree and see if you can functionalize or encapsulate the eventing behavior. Perhaps the data is all that needs to be global in this instance (user credentials), where as the event can be kept isolated.

You could also de-register in the handler itself if this was a one-off event you cared about. It really boils down to your specific need and instance, weak event pattern is the pattern to deal with this application wide but does not mean you have to use that pattern in each and every instance this problem surfaces.

链接地址: http://www.djcxy.com/p/49006.html

上一篇: .net Windows服务本地应用程序数据是不同的,然后在正常的应用程序

下一篇: c#中的事件处理器和应用程序生命周期对象