In what cases are detaching from events necessary? - c#

I'm not sure if I'm entirely clear on the implications of attaching to events in objects.
This is my current understanding, correct or elaborate:
1. Attaching to local class events do not need to be detached
Examples:
this.Closing += new System.ComponentModel.CancelEventHandler(MainWindow_Closing);
public event EventHandler OnMyCustomEvent = delegate { };
I'm assuming that when your object is disposed or garbage collected, the functions are deallocated and would automatically detach from the events.
2. Attaching to objects you no longer need (= null;) have to be detached from
Examples:
Attaching to a timer's Elapsed event, which you only respond to once. I would assume you need to store the Timer in a local variable so you can detached the Elapsed event after the event fires. Thus, declaring the timer in a local method scope like so would result in a leak:
System.Timers.Timer myDataTimer = new System.Timers.Timer(1000);
myDataTimer.Elapsed += new System.Timers.ElapsedEventHandler(myDataTimer_Elapsed);
3. Attaching to events in a local object to your class does not require disposing?
For example, if you had an ObservableCollection that your creates, monitors, and lets die. If you attached to the CollectionChanged event using a local, private function, wouldn't this function deallocate when your class is garbage collected, causing the ObservableCollection to also be freed?
I'm sure I have places where I've stopped using objects and have failed to detach from an event (for example, the timer example I made), so I'm looking for a clearer explanation on how this works.

I think you're making it more complicated than it needs to be. You just need to remember two things:
When you subscribe to an event, the event's "owner" (the publisher) generally keeps a reference to the delegate you subscribe with.
If you use an instance method as the action of a delegate, then the delegate has a reference to its "target" object.
This means that if you write:
publisher.SomeEvent += subscriber.SomeMethod;
Then subscriber won't be eligible for garbage collection before publisher is unless you unsubscribe later.
Note that in many cases, subscriber is just this:
publisher.SomeEvent += myDataTimer_Elapsed;
is equivalent to:
publisher.SomeEvent += this.myDataTimer_Elapsed;
assuming it's an instance method.
There is no reverse relationship just due to event subscription - in other words the subscriber doesn't keep the publisher alive.
See my article on events and delegates for more information, by the way.

The remaining references preventing garbage collection has one more effect that may be obvious but nontheless not yet stated in this thread; the attached event handler will be excuted as well.
I have experienced this a couple of times. One was when we had an application that gradually became slower and slower the longer it run. The application created the user interface in a dynamic fashion by loading user controls. The container made the user controls subscribe to certain events in the environment, and one of these were not unsubscribed from when the controls were "unloaded".
After a while this led to a large number of event listeners being executed each time that particular event was raised. This can of course lead to serious race conditions when a good number of "sleeping" instances suddenly wake up and try to act on the same input.
In short; if you write code to hook up an event listener; make sure that you release as soon as it's not needed any longer. I almost dare to promise it will save you from at least one headache at some point in the future.

The relevant case where you have to unsubscribe from an event is like this:
public class A
{
// ...
public event EventHandler SomethingHappened;
}
public class B
{
private void DoSomething() { /* ... */ } // instance method
private void Attach(A obj)
{
obj.SomethingHappened += DoSomething();
}
}
In this scenario, when you dispose of a B, there will still be a dangling reference to it from obj's event handler. If you want to reclaim the B's memory, then you need to detach B.DoSomething() from the relevant event handler first.
You could run into the same thing if the event subscription line looked like this, of course:
obj.SomethingHappened += someOtherObject.Whatever.DoSomething();
Now it's someOtherObject that's on the hook and can't be garbage collected.

Related

Can an event's publisher unsubscribe its listeners?

In my last question, I asked what would break a self-cleaning block of code designed to remove all subscriptions from an event's delegates field when the event's parent object is disposed. However, I was informed that setting the event to null does exactly what I was trying to do with the code in question, but without the extra cycles and lines of code.
This article demonstrates that setting an event to null (clearing the delegate field) does not guarantee that nothing is listening for it, and that even if the event is set to null, it may still be kept from the garbage collector.
So the question is, is there a way for the publisher to unsubscribe its listeners?
--
For context, I am aware that the listener is normally expected to remove its own subscription when it is done listening, but I would like a little bit more certainty than that, if possible. Also, I occasionally have to deal with code where I'm not entirely sure if all listeners have unsubscribed when the publisher is disposed.
In case it's relevant, the code from my last question is as follows:
public event CustomEventHandler customHandler;
...
///During this object's lifetime, some other object subscribes to this event.
...
///Method used for cleanup
void ClearSubscriptions(CustomEventHandler handler){
if(handler == null){return;}
Delegate[] delegates = handler.GetInvocationList();
foreach(Delegate item in delegates){
handler -= (CustomEventHandler)item;
}
}
This clears the event's delegates list, but I've been told that just setting customHandler = null should do the same. I also thought that this would ensure that nothing was still listening/referencing the event, but that does not seem to be the case, as is explained below.
To summarize the relevant code in the referenced article, the article's example is a form that allows the user to generate an "EventGenerator" object under one of three different conditions:
1.) There is no cleanup on the object's events.
2.) The publisher cleans up by setting the event to null.
3.) The listener cleans up by unsubscribing from the event.
These are controlled by a radio check, so only one condition may be active at a time. The EventGenerator object has an event that is fired when it is created. Each EventGenerator is assigned a number, starting at 0 and incrementing. The form has an event handler that subscribes to this event, and whenever that event is fired, the event handler prints that a new EventGenerator has been created, along with that object's number. Additionally, the form only references one EventGenerator at a time, so whenever a new one is created, the previous one is forgotten.
Under option 1, every time a new one of these objects is created, all objects that have been created fire off an "I've been created" dialog. This is expected since the form is still subscribed to all of these instances, even if they have been dereferenced.
Under option 3, when a new object is created, the form unsubscribes from the previous EventGenerator's event before dereferencing it, so the new object's "created" dialog displays, as well as the old object's "finalized" dialog. This demonstrates that the object has been gathered by the garbage collector and no longer holds any resources.
Option 2 is what confuses me. When option 2 is active, if a new EventGenerator is created, then the old one is disposed. The form does not unsubscribe, but the previous object does set its event to null. The "New Object" dialog is displayed once, with the new object's number. The previous generators are silent, meaning their events aren't being fired, and that is good. However, their "finalized" dialog never fires. This means that, even though the event has been set to null, the EventGenerator is still not eligible for garbage collection, creating a memory leak.
It seems to me that this is probably because the form itself never unsubscribes from the event under option 2. Then, even though the event doesn't really exist anymore, the form is still pointing at it, and that keeps the garbage collector away.
So with that context, I am curious. Is there a way for an event's publisher to unsubscribe its listeners and let Option 2 free up those dereferenced objects?
Also, sorry for this extra information being so verbose!

Is it safe to replace all standard event handler to WeakEventManager or its variants?

Standard event handler (with operator +=) is one of the memory leakage cause (if it is not unregistered/disposed (with -= operator)).
And Microsoft solved it with WeakEventManager and its inheritance like: PropertyChangedEventManager, CollectionChangedEventManager, CurrentChangedEventManager, ErrorsChangedEventManager and so on.
The simple example code with memory leakage is:
public class EventCaller
{
public static event EventHandler MyEvent;
public static void Call()
{
var handler = MyEvent;
if (handler != null)
{
handler(null, EventArgs.Empty);
Debug.WriteLine("=============");
}
}
}
public class A
{
string myText;
public A(string text)
{
myText = text;
EventCaller.MyEvent += OnCall;
// Use code below and comment out code above to avoid memory leakage.
// System.Windows.WeakEventManager<EventCaller, EventArgs>.AddHandler(null, "MyEvent", OnCall);
}
void OnCall(object sender, EventArgs e)
{
Debug.WriteLine(myText);
}
~A()
{
Debug.WriteLine(myText + " destructor");
}
}
void Main()
{
var a = new A("A");
var b = new A("B");
EventCaller.Call();
a = null;
GC.Collect();
EventCaller.Call();
}
The output is:
A
B
+++++++
A
B
+++++++
We can see that the destructor will not be called.
But if we change (by commenting the unused code) from:
EventCaller.MyEvent += OnCall;
to
System.Windows.WeakEventManager<EventCaller, EventArgs>.AddHandler(null, "MyEvent", OnCall);
And the output is:
A
B
+++++++
B
+++++++
A destructor
B destructor
After A is nulled then its event handler will not be called anymore.
A and B will be disposed after not be used anymore without -= operator.
Can I safely replace all += operator with System.Windows.WeakEventManager to avoid memory leakage due to probably missing event unregistration and saving code by should not implement IDisposable?
If it is not really safe, what should I consider or notice?
Can I safely replace all += operator with System.Windows.WeakEventManager to avoid memory leakage due to probably missing event unregistration and saving code by should not implement IDisposable?
Can you? Probably. Should you? Probably not. If you do have a strong reference to an event handler you should prefer unsubscribe from it if the publisher of the event lives longer than the subscriber of the event rather than replacing the strong reference with a weak event. There are side effects of using weak events. One of them is performance. Another is the semantic difference. You may want to refer to the following question and answers about why the implementation of events in the .NET Framework does not use the weak event pattern by default:
Why is the implementation of events in C# not using a weak event pattern by default?
There are certainly certain scenarios where you should use the weak event pattern. One such scenario is the data binding in WPF where a source object is completely independent of the listener object. But this doesn't mean that you should always use the weak event pattern. And it also doesn't mean that you should stop caring about disposing subscriptions in your applications.
1) I would not take code saving as an argument to use the WeakEventManager instead of implementing IDisposable.
2) In case of the Weak event pattern, event handling will continue until the garbage collecor collects the listener. Unreferencing the listener does not stop event handling immediately as explicit unregistering of a strong referenced event handler in the Dispose pattern does.
3) See the Microsoft documentation concerning Weak Event Patterns
The weak event pattern can be used whenever a listener needs to register for an event, but the listener does not explicitly know when to unregister. The weak event pattern can also be used whenever the object lifetime of the source exceeds the useful object lifetime of the listener. (In this case, useful is determined by you.)
If you explicitly know when to unregister the listener, I would prefer the standard events and implement the Dispose pattern. From the event handlers point of view, explicit unregistration has the advantage that the event handling immediately stops while the weak event pattern continues to handle the events (which also could be CPU and memory consuming) until the garbage collector collects the listener.
A specific case where you can't "blindly" substitute a weak event for a normal one was noted in a post by Thomas Levesque:
If you're subscribing to the event with an anonymous method (e.g. a
lambda expression), make sure to keep a reference to the handler,
otherwise it will be collected too soon.
So you can change it to weak as long as you keep a reference to the anonymous handler method / delegate in addition.

Adding and Removing Event Handler in .net

i recently created a sample application, wherein i implemented the events and delegates, when the Properties value is changed this event will raise, i have a question regarding events
Does event objects are created in memory? or they are just static object which gets removed once the event is fired?
Is it necessary to remove the handler once the event is executed, to free-up resources. does removing handler once done, boost's up the application performance, i am talking about the application which are using lots of events
Events do take memory and are not garbage collected until after you unsubscribe from them. They are a common cause of memory leaks.
Events can be both static and instance bound. Subscribers to the event are never removed while the event broadcaster is alive, unless implicitly done so, usually with the -= operator.
Yes, yes and yes. If you don't clean-up your subscribers you have a memory-leak waiting to happen.
If all this is a concern to you perhaps you could look into the WeakEvent pattern.
events are like delegates ( with another layer of protection) .
when you register to an event - you are actually making a reference to another object.
this object can't go through GC because you made a reference to it !
it isnt "un-referenced".
but your object CAN go through GC. ( if un-referenced).
so you end up with memory leak.
you should manually remove the reference .

C# language: why WeakReference or Weak Event Pattern?

I'm reading "The C# Language", 4th edition, it talks about WeakReference and Weak Event Pattern:
CHRISTIAN NAGEL: Memory leaks often result from wrong usage of events. If client objects attach to events but do not detach from them, and the reference to the client object is no longer used, the client object still cannot be reclaimed by the garbage collector because the reference by the publisher remains. This can be avoided by (1) detaching of events when the client object is no longer used, (2) a custom implementation of the add and remove accessors using the WeakReference class holding the delegate, or (3) the Weak Event pattern that is used by WPF with the IWeakEventListener interface.
I have doubts here: Option "(2) WeakReference" brings NO convenience at all, comparing to "option (1) detaching of events explictly", because using WeakReference still need explicitly calls both add and remove.
Otherwise, even if one of the event handler's object was assigned to null, the "orphan" object will still respond to the event - this will cause unexpected behavior.
Note: WeakReference only helps Garbage collection in the way that event handlers' objects will not become affected by event publisher objects; WeakReference does NOT force event handler objects get garbage collected.
Similar issue applies to Weak Event pattern, too.
Maybe this is a bit abstract, take Josh Smith's Mediator pattern (http://joshsmithonwpf.wordpress.com/2009/04/06/a-mediator-prototype-for-wpf-apps/) as example.
public class Mediator //...
{
public void Register(object message, Action<object> callback)
{
// notice: Mediator has no Unregister method
}
public void NotifyColleagues(object message, object parameter)
{
// ...
}
}
public class ObjectA //...
{
public string ObjectAText
{
get { return _objectAText; }
set
{
//...
_mediator.NotifyColleagues(MediatorMessages.ObjectASaidSomething, _objectAText);
}
}
}
public class ObjectB //...
{
//...
public ObjectB(Mediator mediator)
{
//...
_mediator.Register(
MediatorMessages.ObjectASaidSomething,
param =>
{
// handling event ObjectASaidSomething
});
}
}
If we have
ObjectA objectA = new ObjectA();
ObjectB objectB1st = new objectB();
objectA.ObjectAText = "John"; // objectB1st will respond to this event.
objectB1st = null; // due to delay of garbage collection, the object is actually still in memory
ObjectB objectB2nd = new objectB();
objectA.ObjectAText = "Jane"; // both objectB1st and objectB2nd will respond to this event!
Wouldn't the last line caused an unexpected behavior, due to the WeakReference?
But if the Mediator class provides "Unregister" method (actually I implemented one), "option (2) WeakReference" will be no difference to "option (1) detaching of events explictly". (Mediator itself is still a useful pattern, that can penetrate hierarchy of WPF or MVVM component layers )
If I understand what you are asking, then there is a need for some clarification.
Otherwise, even if one of the event handler's object was assigned to
null, the "orphan" object will still respond to the event - this will
cause unexpected behavior.
Not really. This is not unexpected behavior. It is totally expected for the object to be called, if you do not unregister it explicitly.
The whole idea of the weak events is a safety net for not keeping objects in memory only because they are subscribed to an event. It has nothing to do with unregistering the object from the event when it goes out of scope.
If you need to do the later, either use IDisposable pattern and "using" construct for the subscribers, or do explicit unsubscribe.
I.e. weak events are solution for a very specific problem - to allow garbage collection of objects, which were subscribed to a long living object (like GUI or some static class).
Weak events are not about automatic unsibscribing from an even in the moment the object goes out of scope.
If the event subscriber and publisher both cooperate, it is possible to implement a reasonable weak-event pattern in .net without need for Reflection or other CLR tricks. It would be possible for an event subscriber to implement a weak-event pattern unilaterally if events' unsubscribe methods were required to function correctly if called by the finalizer thread, but unfortunately such an expectation is not reasonable when subscribing to events from an unknown class (e.g. an INotifyPropertyChanged). The trick would be for anyone who was really "interested" in an object to hold a strong reference to a wrapper, and for event handlers and other things to hold a reference to the object's "guts". The wrapper could hold a reference to both the guts and to an object with a Finalize method that would unsubscribe the event.

unsubscribing events from class?

I need bit of advise on best practice for this type of scenario. I searched but dont find any satisfying answer.
We use a 3rd party (.net) DLL in our winforms project. It raises some events and we subscribe to. Question is , do i need to explicitly unsubscribe these events in my class ?
BTW we both use .net framework 4. Thanks for the advise.
some sample code ...
public class MyClientCode: IDisposable
{
private readonly 3rdParty.TheirClass _theirClass;
public MyClientCode()
{
_theirClass = new _theirClass()
_theirClass.ReadData += ReadDataEvent;
}
public void SomeOtherMethod()
{
//some other code
}
public void ReadDataEvent()
{
//some code
}
public void Dispose()
{
_theirClass.ReadData -= ReadDataEvent;
}
}
and in the button click event, i do ...
MyClientCode code = new MyClientCode();
code.SomeOtherMethod();
If you don't unsubscribe, the object that subscribed to the event will not be garbage collected (it will be kept in memory). This can create memory leaks and lead to excessive memory usage.
However, if the event has a shorter or same lifetime as the class that contains it, in your case, the memory will be collected properly. If you have another object reference a non-private event, then you will run into issues.
See MSDN:
Until you unsubscribe from an event, the multicast delegate that underlies the event in the publishing object has a reference to the delegate that encapsulates the subscriber's event handler. As long as the publishing object holds that reference, your subscriber object will not be garbage collected.
Note that you don't need to unsubscribe if you are exiting your application, only in cases where it shouldn't be held in memory. (For example, when you close a window in your application, you should unsubscribe from any events, or else the window will still be held in memory.) If the containing object is destroyed manually, the events will also be destroyed.

Categories

Resources