C# still hooked to an event after unhooking - c#

I am currently debugging a big (very big!) C# application that contains memory leaks. It mainly uses Winforms for the GUI, though a couple of controls are made in WPF and hosted with an ElementHost. Until now, I have found that many of the memory leaks were caused by events not being unhooked (by calling -=) and I've been able to solve the problem.
However, I just came across a similar problem. There is a class called WorkItem (short lived) which in the constructor registers to events of another class called ClientEntityCache (long lived). The events were never unhooked and I could see in .NET profiler that instances of WorkItem were being kept alive when they shouldn't because of those events. So I decided to make WorkItem implement IDisposable and in the Dispose() function I unhook the events this way:
public void Dispose()
{
ClientEntityCache.EntityCacheCleared -= ClientEntityCache_CacheCleared;
// Same thing for 10 other events
}
EDIT
Here is the code I use for subscription:
public WorkItem()
{
ClientEntityCache.EntityCacheCleared += ClientEntityCache_CacheCleared;
// Same thing for 10 other events
}
I also changed the code for unregistering to not call new EntityCacheClearedEventHandler.
END OF EDIT
I made the calls to Dispose at the proper places in the code that uses WorkItem and when I debug I can see that the function is really being called and I do -= for every event. But I still get a memory leak and my WorkItems still stay alive after being Disposed and in .NET profiler I can see that the instances are kept alive because the event handlers (like EntityCacheClearedEventHandler) still have them in their invocation list. I tried to unhook them more than once (multiple -=) just to make sure they were not hooked more than once but this doesn't help.
Anyone has an idea why this is happening or what I could do to solve the problem?
I suppose I could change the event handlers to use weak delegates but this would require to mess a lot with a big pile of legacy code.
Thanks!
EDIT:
If this helps, here is the root path described by .NET profiler:
lots of things point on ClientEntityCache, which points to EntityCacheClearedEventHandler, which points to Object[], which points to another instance of EntityCacheClearedEventHandler (I don't understand why), which points to WorkItem.

It might be that multiple different delegate functions are wired to the event. Hopefully the following little example will make it clearer as to what I mean.
// Simple class to host the Event
class Test
{
public event EventHandler MyEvent;
}
// Two different methods which will be wired to the Event
static void MyEventHandler1(object sender, EventArgs e)
{
throw new NotImplementedException();
}
static void MyEventHandler2(object sender, EventArgs e)
{
throw new NotImplementedException();
}
[STAThread]
static void Main(string[] args)
{
Test t = new Test();
t.MyEvent += new EventHandler(MyEventHandler1);
t.MyEvent += new EventHandler(MyEventHandler2);
// Break here before removing the event handler and inspect t.MyEvent
t.MyEvent -= new EventHandler(MyEventHandler1);
t.MyEvent -= new EventHandler(MyEventHandler1); // Note this is again MyEventHandler1
}
If you break before the removal of the event handler you can view the invocation list in the debugger. See below, there are 2 handlers, one for MyEventHandler1 and another for the method MyEventHandler2.
Now after removing the MyEventHandler1 twice, MyEventHandler2 is still registered, because there is only one delegate left it looks a little different, it is no longer showing in the list, but until the delegate for MyEventHandler2 is removed it will still be referenced by the event.

When unhooking an event, it needs to be the same delegate. Like this:
public class Foo
{
private MyDelegate Foo = ClientEntityCache_CacheCleared;
public void WorkItem()
{
ClientEntityCache.EntityCacheCleared += Foo;
}
public void Dispose()
{
ClientEntityCache.EntityCacheCleared -= Foo;
}
}
The reason is, what you are using is syntactic sugar for this:
public class Foo
{
public void WorkItem()
{
ClientEntityCache.EntityCacheCleared +=
new MyDelegate(ClientEntityCache_CacheCleared);
}
public void Dispose()
{
ClientEntityCache.EntityCacheCleared -=
new MyDelegate(ClientEntityCache_CacheCleared);
}
}
So the -= doesn't unhook the original one you subscribed with because they are different delegates.

Are you unhooking the right reference? When you unhook using -= no error is produced and if you're unhooking events which aren't hooked nothing will happen. However if you add using += you'll get an error if the event is already hooked. Now, this is only a way for you to diagnose the problem but try adding the events instead and if you DONT get an error the problem is that your unhooking the event with the wrong reference.

Dispose won't get called by the GC if the instance is being kept alive by the event handlers, as it is still being referenced by the source of the events.
If you called your Dispose method yourself, the references would then go out of scope.

Maybe try:
public void Dispose()
{
ClientEntityCache.EntityCacheCleared -= ClientEntityCache_CacheCleared;
// Same thing for 10 other events
}
You are creating a new event handler and removing it from the delegate - which effectively does nothing.
Remove the event subscription by removing reference to the original subscribing event method.
You could always just set your eventhandler = delegate {}; In my opinion, that would be better than null.

Related

Trouble with delegates/ events in Unity

I've been having trouble with using delegates and events in Unity. I am familiar with subscribing and unsubscribing.
The problem i have is a stack overflow exception. However my Console outputs another message while not even in playmode. I am confident this log is tied to the stackoverflow exception, because it happened at the same time.
What is also curious, is that the error just started happening, without me touching that part of the code for a while. I changed nothing in the subscribing of the event.
Note that i had this exact same problem earlier in another project and ended up ditching event subscription.
Do note, i am not talking about the UnityEvent. I'm talking about the scripting delegate & event.
Here is the definition of the delegate and event code:
public delegate void gameStart();
public event gameStart OnGameStart;
public delegate void gameEnd();
public event gameEnd OnGameEnd;
Here is a subscriber:
public override void OnInitialize()
{
GameManager.Instance.OnGameEnd += StopSound;
GameManager.Instance.OnGameStart += PlaySwipeClip;
}
public void PlaySound(AudioClip clip, bool doNotStopCurrent = false)
{
if (doNotStopCurrent)
{
popupAudioSource.clip = clip;
popupAudioSource.Play();
// AudioSource.PlayClipAtPoint(clip, Vector3.zero, 1f);
}
else
{
mainAudioSource.clip = clip;
mainAudioSource.Play();
}
}
public void PlaySwipeClip()
{
mainAudioSource.clip = SwipeClip;
mainAudioSource.Play();
}
I Only subscribe to the events once (I use the singleton pattern, OnInitialize() is called in Awake()).
I am positive that the subscription does not happen twice.
I never unsubscribe to the events. Reason for this is that I use the same scene and "Manager" objects for the entire app's lifecycle.
Is there something I am missing here? Should i unsubscribe in the OnDestroy?
Somehow i have a feeling that subscriptions are persistent between the lifecycles. The error goes away for a while when i rename the event variable.
Also I have tried setting all the events to null explicitly in the awake method, however this does not seem to resolve anything.
You have to unsubscribe otherwise you will leak memory. It is recommended to subscribe OnEnable() and unsubscribe OnDisable().

WeakEventManager - event handler is not called

I am not able to reproduce the issue (and project is too big to post it here, plus I am not sure what are related parts to post) and I need ideas of what could go wrong here.
I have abstract class with static event
public abstract partial class A : Base
{
public static event EventHandler Test;
public static void OnTest() => Test?.Invoke(null, EventArgs.Empty);
}
Then I subscribe to this event normally and using WeakEventManager:
A.Test += (s, e) => { };
WeakEventManager<A, EventArgs>.AddHandler(null, nameof(A.Test), (s, e) => { });
And for some reasons weak event handler doesn't get fired when OnTest() is called. Everything (invoke and handlers) are operating in the UI thread.
I've set breakpoints:
On AddHandler(), it runs and the instance of class then persist.
On Invoke(), it runs when OnTest is called, I can see 2 subscribers if I call Test.GetInvocationList() one of them is DeliverEvent() from WeakEventManager, so event was registered and Invoke() should call weak event handler.
Inside normal event handler, it runs.
Inside weak event handler, nothing, this breakpoint never get hit.
Any ideas of why would this occur or what should I investigate?
I've tried to look into .net sources, to find answers there, but there is ProtectedAddHandler which sources I can't find...
I found it, but what is the next? Abstract method, who implements it?...
WeakEventManager ... not working event handler ...
To whoever face this issue, the problem is this: you must rise static event with null as sender! E.g. in my case it was (use this to reproduce issue with code in the question):
public static void OnTest() => Test?.Invoke("whatever", EventArgs.Empty);
This case will be handled by normal subscriber without any problem.
But in case of WeakEventManager it must be a null (special case), otherwise your event handler will not work.

DebuggerEvents.OnEnterBreakMode is not triggered in the Visual Studio Extension Package

I wrote a visual studio extension package that subscribes to DebuggerEvents.OnEnterBreakMode event. But this event is never get raised.
Here is some code:
protected override void Initialize()
{
base.Initialize();
applicationObject = (DTE2) GetService(typeof (DTE));
applicationObject.Events.BuildEvents.OnBuildDone += BuildEventsOnOnBuildDone;
applicationObject.Events.DebuggerEvents.OnEnterBreakMode += DebuggerEventsOnOnEnterBreakMode;
}
But method DebuggerEventsOnOnEnterBreakMode is never called. Method BuildEventsOnOnBuildDone is called.
Why this can happen?
I know this sounds silly but in order to listen to the DebuggerEvents events you need to maintain a reference to DebuggerEvents itself.
DebuggerEvents _debuggerEvents;
protected override void Initialize() {
applicationObject = (DTE2) GetService(typeof (DTE));
_debuggerEvents = applicationObject.Events.DebuggerEvents;
_debuggerEvents.OnEnterBreakMode += DebuggerEventsOnOnEnterBreakMode
The reason for this is subtle. DebuggerEvents is actually a COM / CCW object which is created on demand when the DTE.DebuggerEvents property is accessed. The event handler code doesn't keep the CCW alive hence the next GC potentially collects the DebuggerEvents property and takes the event handler with it.
It's a really strange bug that is specific to CCW and events. I've heard it referred to as "the most vexing bug ever" and it's not far from the truth

What kind of situations I'd need to use events of C#

I am studying events in C# but there are not much articles or information that show me where or what kinda position I'd need to use events in.
Could some one give me real world example that makes them more understandable.
Thanks in advance.
As Chris Gray said, one use is to signal when something has happened that your code didn't directly call. The most common cause here is probably user actions on the GUI. Another example might be an asynchronous operation completing on another thread.
The other reason to use events is when you don't know who might be interested in what has just happened. The class raising the event doesn't need to know (at design time) anything about how many instances of what other classes might be interested.
class Raiser {
public DoSomething() {
//Do something long winded.
OnDidSomething(new DidSomethingEventArgs());
}
public EventHandler<DidSomethingEventArgs> DidSomething;
private OnDidSomething(DidSomethingEventArgs e) {
if (DidSomething != null)
DidSomething(this, e);
}
}
Obviously, you also need to define the DidSomethingEventArgs class which passes on the relevant data about the event. This also illustrates a common naming convention for events. If the event is called X, then the event is only ever raised in a method called OnX and any data it passes on is an instance of class XEventArgs. Note that an event can be null if no listeners are subscribed to it, hence the check just before we raise the event.
Note that this class knows nothing about what other classes might be interested in the fact that it did something. It simply announces the fact that it has done it.
Multiple classes can then listen out for the event:
class ListenerA {
private Raiser r;
ListenerA(Raiser r) {
this.r = r;
r.DidSomething += R_DidSomething;
}
R_DidSomething(object sender, DidSomethingEventArgs e) {
//Do something with the result.
}
}
And:
class ListenerB {
private Raiser r;
ListenerB(Raiser r) {
this.r = r;
r.DidSomething += R_DidSomething;
}
R_DidSomething(object sender, DidSomethingEventArgs e) {
//Do something with the result.
}
}
Now, when the DoSomething method is called on the Raiser instance, all instances of ListenerA and ListenerB will be informed via the DidSomething event. Note that the listener classes could easily be in different assemblies to the raiser. They need a reference back to the raiser's assembly but it doesn't need a reference to its listeners' assemblies.
Note that the above simple Raiser example may cause you some problems in a multi-threaded program. A more robust example would use something like:
class Raiser {
public DoSomething() {
//Do something long winded.
OnDidSomething(new DidSomethingEventArgs());
}
#region DidSomething Event
private object _DidSomethingLock = new object();
private EventHandler<DidSomethingEventArgs> _DidSomething;
public EventHandler<DidSomethingEventArgs> DidSomething {
add { lock(_DidSomethinglock) _DidSomething += value; }
remove { lock(_DidSomethinglock) _DidSomething -= value; }
}
OnDidSomething(DidSomethingEventArgs e) {
EventHandler<DidSomethingEventArgs> handler;
lock (_DidSomethingLock)
handler = _DidSomething;
if (handler == null)
return;
try {
DidSomething(this, e);
} catch (Exception ex) {
//Do something with the exception
}
}
#endregion
}
This ensures that another thread adding or removing a listener while you are in the middle of raising the event doesn't cause problems.
The simple listeners used here will also cause memory leaks if instances of the listener classes are being created and destroyed. This is because the Raiser instance gets passed (and stores) a reference to each listener as they subscribe to the event. This is enough to prevent the garbage collector from properly tidying up the listeners when all explicit references to them are removed. The best way round this is probably to make the listeners implement the IDisposable interface and to unsubscribe from the events in the Dispose method. Then you just need to remember to call the Dispose method.
The most practical example I generally see is User Interactivity. Let's use a Button as a specific example. When the button is clicked, you obviously want something to happen. Let's say we call "SaveSettings()". However, we don't want to hard-code "SaveSettings()" into the button. The buttom would be commanding SaveSettings() to occur. Obviously, this prevents the button from being reusable - we can't use a button which calls SaveSettings() anywhere but the settings dialog. To avoid writing the same button code for every button, each one calling a different function, we use an event.
Instead of the button calling a function directly, the button announces that it has been clicked. From there, the button's responsibility is over. Other code can listen for that announcement, or event, and do something specific.
So in our SaveSettings example, the settings dialog code finds the "OK" button and listens for its "I got clicked" announcement, and when it is fired, calls SaveSettings().
Events can become very powerful because any number of different listeners can wait for the same event. Many things can be invoked by the event.
Sure thing. think of an event as the notification that occurs when something completes in the system that your code didn’t directly call. In C# it's really easy to get code to run when an event "fires"
For example when a user presses a button an event will be raised or when a background network operation completes. In C# you use the += semantics to attach to the event that will be “signaled” when the event fires.
I made you a simple C# winforms program – in it I added a button using the Visual Studio “Designer” (I just dragged a button from the Toolbox to the Window).
You’ll see the line “button1.Click” – in this case I want to do something when the “Click” event is raised.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace events
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += new EventHandler(button1_Click);
}
void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Hi!");
}
}
}
You’ll also see other kinds of events in practice for example:
Network operation has completed (WebClient.DownloadFileCompleted)
User Interfaces (resizing windows for example)
Timers (set off the timer in 10 minutes)
Let's say you are developing a UI. You create a widget and you add it to the main form. When something happens in your widget, you can use events to trigger some action on the form - disabling other buttons, etc.
Just like how a button's click event works.

Is it necessary to explicitly remove event handlers in C#

I have a class that offers up a few events. That class is declared globally but not instanced upon that global declaration--it's instanced on an as-needed basis in the methods that need it.
Each time that class is needed in a method, it is instanced and event handlers are registered. Is it necessary to remove the event handlers explicitly before the method goes out of scope?
When the method goes out of scope, so goes the instance of the class. Does leaving event handlers registered with that instance that is going out of scope have a memory footprint implication? (I'm wondering if the event handler keeps the GC from seeing the class instance as no longer being referenced.)
In your case, everything is fine. It's the object which publishes the events which keeps the targets of the event handlers live. So if I have:
publisher.SomeEvent += target.DoSomething;
then publisher has a reference to target but not the other way round.
In your case, the publisher is going to be eligible for garbage collection (assuming there are no other references to it) so the fact that it's got a reference to the event handler targets is irrelevant.
The tricky case is when the publisher is long-lived but the subscribers don't want to be - in that case you need to unsubscribe the handlers. For example, suppose you have some data transfer service which lets you subscribe to asynchronous notifications about bandwidth changes, and the transfer service object is long-lived. If we do this:
BandwidthUI ui = new BandwidthUI();
transferService.BandwidthChanged += ui.HandleBandwidthChange;
// Suppose this blocks until the transfer is complete
transferService.Transfer(source, destination);
// We now have to unsusbcribe from the event
transferService.BandwidthChanged -= ui.HandleBandwidthChange;
(You'd actually want to use a finally block to make sure you don't leak the event handler.) If we didn't unsubscribe, then the BandwidthUI would live at least as long as the transfer service.
Personally I rarely come across this - usually if I subscribe to an event, the target of that event lives at least as long as the publisher - a form will last as long as the button which is on it, for example. It's worth knowing about this potential issue, but I think some people worry about it when they needn't, because they don't know which way round the references go.
EDIT: This is to answer Jonathan Dickinson's comment. Firstly, look at the docs for Delegate.Equals(object) which clearly give the equality behaviour.
Secondly, here's a short but complete program to show unsubscription working:
using System;
public class Publisher
{
public event EventHandler Foo;
public void RaiseFoo()
{
Console.WriteLine("Raising Foo");
EventHandler handler = Foo;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
else
{
Console.WriteLine("No handlers");
}
}
}
public class Subscriber
{
public void FooHandler(object sender, EventArgs e)
{
Console.WriteLine("Subscriber.FooHandler()");
}
}
public class Test
{
static void Main()
{
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();
publisher.Foo += subscriber.FooHandler;
publisher.RaiseFoo();
publisher.Foo -= subscriber.FooHandler;
publisher.RaiseFoo();
}
}
Results:
Raising Foo
Subscriber.FooHandler()
Raising Foo
No handlers
(Tested on Mono and .NET 3.5SP1.)
Further edit:
This is to prove that an event publisher can be collected while there are still references to a subscriber.
using System;
public class Publisher
{
~Publisher()
{
Console.WriteLine("~Publisher");
Console.WriteLine("Foo==null ? {0}", Foo == null);
}
public event EventHandler Foo;
}
public class Subscriber
{
~Subscriber()
{
Console.WriteLine("~Subscriber");
}
public void FooHandler(object sender, EventArgs e) {}
}
public class Test
{
static void Main()
{
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();
publisher.Foo += subscriber.FooHandler;
Console.WriteLine("No more refs to publisher, "
+ "but subscriber is alive");
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("End of Main method. Subscriber is about to "
+ "become eligible for collection");
GC.KeepAlive(subscriber);
}
}
Results (in .NET 3.5SP1; Mono appears to behave slightly oddly here. Will look into that some time):
No more refs to publisher, but subscriber is alive
~Publisher
Foo==null ? False
End of Main method. Subscriber is about to become eligible for collection
~Subscriber
In your case, you are fine. I originally read your question backwards, that a subscriber was going out of scope, not the publisher. If the event publisher goes out of scope, then the references to the subscriber (not the subscriber itself, of course!) go with it and there is no need to explicitly remove them.
My original answer is below, about what happens if you create an event subscriber and let it go out of scope without unsubscribing. It does not apply to your question but I'll leave it in place for history.
If the class is still registered via event handlers, then it is still reachable. It is still a live object. A GC following an event graph will find it connected. Yes, you will want to explicitly remove the event handlers.
Just because the object is out of scope of its original allocation does not mean it is a candidate for GC. As long as a live reference remains, it is live.

Categories