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.
Related
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.
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.
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.
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.
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.