EventHandlers and Anonymous Delegates / Lambda Expressions - c#

I'm hoping to clear some things up with anonymous delegates and lambda expressions being used to create a method for event handlers in C#, for myself at least.
Suppose we have an event that adds either an anonymous delegate or a lambda expression (for you lucky crowds that can use newer versions of .NET).
SomeClass.SomeEvent += delegate(object o, EventArg e) { /* do something */ };
I have read that people in the past have forgotten about events that still have handlers which prevent the class from being garbage collected. How would one go about removing the added handler without just setting SomeEvent to null within the class. Wouldn't the following be an entirely new handler?
SomeClass.SomeEvent -= delegate(object o, EventArg e) { /* do something */ };
I could see storing the anonymous delegate or lambda expression in a variable. But that, to me at least, seems to defeat the entire purpose of being able to simply and succinctly add an event handler.
SomeEventDelegate handler = new SomeEventDelegate(delegate(object o, EventArg e) { /* do something */ });
SomeClass.SomeEvent += handler;
// ... stuff
SomeClass.SomeEvent -= handler;
Again, I understand that you could just do...
public override Dispose(bool disposing)
{
_someEvent = null;
this.Dispose();
}
But I'm more interesting with just removing the dynamically created method from the event. Hopefully someone can shed some light onto this for me. Thanks!

If object X has an event handler whose target is object Y, then object X being alive means that object Y can't be garbage collected. It doesn't stop object X from being garbage collected.
Normally when something is disposed, it will become garbage pretty soon anyway, which means you don't have a problem.
The problem with events and GC is if you forget to remove a subscribed handler from a different object - i.e. you have a listener which is disposed, but will never be garbage collected because there's still a reference to it from the event in a different object.

I think the problem is you seem to be proceeding from the assumption that having a delegate assigned to an object's event prevents it from being GCed.
This as a simple statement is not true.
With that said the perceived problem disappears.
Initially in garbage collection everything is garbage. The GC runs through every thing currently available globally and on each stack and from these those other objects that they are referencing and so on, marking each as not garbage.
How would such a graphing process manage to arrive at this object?

You can't.
Just like you can't create anonymous type outside of its scope (except for some compiler tricks).
That's why it's called anonymous.
You have to save a reference somewhere... or use reflection.

Related

Can event listener of WeakEvent be deleted by garbage collection any time?

I'm looking for a solution avoiding memory leaks when using events (which may occur if the listener is never removed from the event source. I found this code project article describing a WeakEvent class like this:
sealed class EventWrapper
{
SourceObject eventSource;
WeakReference wr;
public EventWrapper(SourceObject eventSource,
ListenerObject obj) {
this.eventSource = eventSource;
this.wr = new WeakReference(obj);
eventSource.Event += OnEvent;
}
void OnEvent(object sender, EventArgs e)
{
ListenerObject obj = (ListenerObject)wr.Target;
if (obj != null)
obj.OnEvent(sender, e);
else
Deregister();
}
public void Deregister()
{
eventSource.Event -= OnEvent;
}
}
As far a I understood the listener object is wrapped in a WeakReference, which is not considered as a reference to the event listener from the Garbage Collectors' point of view.
My question: When using this pattern, is it possible that the Garbage Collector deletes ListenerObject obj though no event was fired by the event source beforehand? In that case, the whole pattern becomes indeterministic since the fired event is not forwarded to the ListenerObject, because the Garbage Collector deleted it (because there is only a WeakReference pointing to it). If this is correct why should I use a pattern like this anyway?
Thx
Yes, if the WeakReference is the only thing which holds a reference to ListenerObject, then ListenerObject can be GC'd at any point.
You would use a pattern like this if your EventWrapper class is not the only thing which has a reference to ListenerObject, but your EventWrapper doesn't know when that other thing is going to release its reference to ListenerObject.
For example, ListenerObject might be a UI control which appears on a screen, and the EventWrapper might be owned by a singleton service. The UI control will stay alive as long as that screen is shown, but will be released when the user changes the screen. The service might not know when that happens. Using a weak event pattern means that you don't accidentally end up with a memory leak in this case.
Note, if you do want to implement the weak event pattern, use a WeakEventManager as detailed in this article.

Unsubscribe to lambda event [duplicate]

I have the following code to let the GUI respond to a change in the collection.
myObservableCollection.CollectionChanged += ((sender, e) => UpdateMyUI());
First of all is this a good way to do this?
Second: what's the code to unsubscribe from this event? Is it the same but with -= (and then the complete anonymous method again)?
First of all... yes its a good way of doing it, it's clean, small form and easy to read & understand... the caveat of course is "Unless you later want to unsubscribe".
I believe Jon Skeet pointed out before that
"the specification explicitly doesn't guarantee the behaviour either way when it comes to equivalence of delegates created with anonymous methods."
So if you need to unsubscribe from the event at a later time, you'd be best to actually create a delegate instance so you can hang onto the reference for later.
var myDelegate = delegate(sender, e){UpdateMyUI()};
myObservableCollection.CollectionChanged += myDelegate;
myObservableCollection.CollectionChanged -= myDelegate;
If you need to unsubscribe from an event, you need an instanced reference. Unfortunately, that means you can't use that particular syntax.
It's an ok way to go, unless myObservableCollection is going to live longer than 'this', in which case you could end up with a memory leak, as the delegate which is created behind the scenes will conserve a reference to your 'this', which will keep it alive. If you are repeatedly creating and 'destroying' whatever is listening to the event, you will find that they aren't being collected by the garbage collector.
If this is a problem, you can go the route suggested in the answers, conserving a reference to the handler, which you must create first.
Another solution is to use weak references to create an event handler which will allow the subscriber to be collected if there are not other references. I've explored this solution in this question and answer.

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.

How to unsubscribe from an event which uses a lambda expression?

I have the following code to let the GUI respond to a change in the collection.
myObservableCollection.CollectionChanged += ((sender, e) => UpdateMyUI());
First of all is this a good way to do this?
Second: what's the code to unsubscribe from this event? Is it the same but with -= (and then the complete anonymous method again)?
First of all... yes its a good way of doing it, it's clean, small form and easy to read & understand... the caveat of course is "Unless you later want to unsubscribe".
I believe Jon Skeet pointed out before that
"the specification explicitly doesn't guarantee the behaviour either way when it comes to equivalence of delegates created with anonymous methods."
So if you need to unsubscribe from the event at a later time, you'd be best to actually create a delegate instance so you can hang onto the reference for later.
var myDelegate = delegate(sender, e){UpdateMyUI()};
myObservableCollection.CollectionChanged += myDelegate;
myObservableCollection.CollectionChanged -= myDelegate;
If you need to unsubscribe from an event, you need an instanced reference. Unfortunately, that means you can't use that particular syntax.
It's an ok way to go, unless myObservableCollection is going to live longer than 'this', in which case you could end up with a memory leak, as the delegate which is created behind the scenes will conserve a reference to your 'this', which will keep it alive. If you are repeatedly creating and 'destroying' whatever is listening to the event, you will find that they aren't being collected by the garbage collector.
If this is a problem, you can go the route suggested in the answers, conserving a reference to the handler, which you must create first.
Another solution is to use weak references to create an event handler which will allow the subscriber to be collected if there are not other references. I've explored this solution in this question and answer.

In what cases are detaching from events necessary?

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.

Categories

Resources