unsubscribing events from class? - c#

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.

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.

Do I need to unsubscribe from a GestureRecogniser in Xamarin.Forms?

So I have the following Control, extended from Label
public Hyperlink()
{
var tapGesture = new TapGestureRecognizer();
tapGesture.Tapped += TapGesture_Tapped;
this.GestureRecognizers.Add(tapGesture);
}
Now my question is, do I need to unhook the GestureRecogniser?
My understanding of GarbageCollection is that because the Hyperlink object is in charge of the tapGesture it should be able to dispose of it; but this is the world of Xamarin.Forms where anything goes.
So do I need the Dispose code to avoid a potential memory leak and avoid keeping the object alive
public void Dispose()
{
if (this.GestureRecognizers.Count > 0)
{
var tapGesture = this.GestureRecognizers[0] as TapGestureRecognizer;
tapGesture.Tapped -= TapGesture_Tapped;
this.GestureRecognizers.Clear();
}
}
This link, as well as this link say that I should be removing GestureRecognisers but does not expand on why
According to Cross-Platform Performance, suggest you unsubscribe from GestureRecogniser.
To prevent memory leaks, events should be unsubscribed from before the subscriber object is disposed of. Until the event is unsubscribed from, the delegate for 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 this reference, garbage collection will not reclaim the subscriber object memory.
Unless you use persistent pages, you do not need to manually dispose of your gesture recognizer. it will be destroyed when whatever page was using it is popped and collected by GC.
If it puts you at ease, you can still manually dispose of it and it won't hurt anything, but it is not required.

C# Dispose(), unsubscribe from events

Is this the right away to call dispose and unsubscribe from events in this context? context_ is used to manage a simple statemachine that we start and stop essentially by creating a new one.
class ClassA
{
StateContext context_;
void SomeMethod()
{
if(context_ != null)
context_.Dispose();
context_ = new StateContext();
}
class StateContext : IDisposable
{
SubClassA()
{
//Subscribe to an event
}
void Dispose()
{
//unsubscribe to an Event
}
}
}
A well-behaved object should not require cleanup beyond calling Dispose. If an object subscribes to events from other objects that may outlive it, it must (to be well-behaved) ensure that those events get cleaned up somehow. This may be done either be using weak events, or by having Dispose take care of the event subscriptions.
Note that the term "unmanaged resource" has only minimal relation to the term "unmanaged code", and that normal events from long-lived objects are unmanaged resources. As such, even though events have nothing to do with unmanaged code, it is entirely right and proper to use IDisposable to clean them up. Indeed, I would suggest that such cleanup should be considered obligatory unless some other means exists to ensure cleanup (e.g. events are handled with a weak-event manager, or the object whose event is subscribed won't outlive the subscriber). WinForms code is often sloppy, on the presumption that event publishers won't outlive subscribers, but that doesn't mean such sloppiness should be considered desirable.

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.

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