Tag: event handlers

Events: Demystifying Common Memory Leaks

Events: Demystifying Common Memory Leaks

Background

If you’ve poked through my previous postings, you’ll probably notice that I love using events when I program. If I can find a reason to use an event, I probably will. I think they’re a great tool that can really help you with designing your architectures, but there are certainly some common problems people run into when they use events. The one I want to address today has to do with memory leaks. That’s right. I said it. Memory leaks in your .NET application. Just because it’s a managed language doesn’t mean your code can’t be leaking memory! And now that I’ve got your attention, let’s see how events might be causing some leakage in your application.

(There is source that you can download and run. Check the summary section at the end!)

Instance-Scope Event Handlers

One of the most common ways to set up an EventHandler in C# is by having them defined for the entire scope of the instance. Consider for a moment the form designer in Visual Studio. When you double click on controls you get some handler created for the default event on that control. See how the EventHandler was declared though? You get a method declared that has a sender and some type of EventArgs. Pretty standard stuff here and there’s nothing ground-breaking about it. So what’s the problem with this method?

Well, there’s nothing wrong with it as long as you know how to clean up after yourself. Consider the following two classes:


private class ObjectWithEvent
{
    ~ObjectWithEvent()
    {
        Console.WriteLine(this + " is being finalized.");
    }

    public event EventHandler<EventArgs> Event;

    public void UnhookAll()
    {
        Event = null;
    }
}

private class ObjectThatHooksEvent
{
    public ObjectThatHooksEvent(ObjectWithEvent objectWithEvent)
    {
        objectWithEvent.Event += ObjectWithEvent_Event;
    }

    ~ObjectThatHooksEvent()
    {
        Console.WriteLine(this + " is being finalized.");
    }

    private void ObjectWithEvent_Event(object sender, EventArgs e)
    {
        // some fancy event
    }
}

The first class has an event that our second class can hook onto. You’ll notice in the second class that I’ve defined an instance-scope handler that we can hook up. This is the exact same syntax for declaring an event handler that you’d get from the form designer if you’re doing GUI programming.

The danger with this setup is that until you unhook the event, the object that hooks onto the event will not be freed. “Well, no problem!” is what you might be thinking. You know how to solve that. You can just unhook the event in the second class’s finalizer/deconstructor.

…Except that won’t work. The finalizer will not get called on the instance of the second class until the event has been unhooked! It’s a bit of a chicken-or-the-egg problem, but it makes sense. A finalizer will only be called when the reference is being cleaned up, but the instance can’t be marked for cleaning because something is still using its event handler. See why this can get a bit dangerous?

Anonymous Delegate (No Parent Reference)

So this is an example of hooking events where you won’t get a leak. Why am I showing it? Well, in the next section I’ll make a small tweak to it which will make it behave just like the first scenario I described.

Let’s assume we have two classes again. I’ll use the first class from my first example (the object with the event) and this new class here that we’ll use to hook onto the event:

private class HookWithAnonymousDelegate
{
    public HookWithAnonymousDelegate(ObjectWithEvent objectWithEvent)
    {
        objectWithEvent.Event += (sender, args) =>
        {
            // handle your event
            // (this one is special because it doesn't use anything related to the instance)
            Console.WriteLine("Event being called!");
        };
    }

    ~HookWithAnonymousDelegate()
    {
        Console.WriteLine(this + " is being finalized.");
    }
}

Notice the difference from the first example? I’ve hooked up an anonymous method (using a lambda expression) to our event instead of declaring an instance-scope event handler. It’s a small change, and for the most part, I might argue that this is just a stylistic thing. If you don’t ever plan on unhooking the event then it’s not such a big deal to go with anonymous methods, but if your method body grows pretty big the code can definitely get unsightly.

Anyway… sweet! We just hooked up to our event and we don’t have the scary leak situation that we did in the first scenario. How cool is that? Well…

Anonymous Delegate (With Parent Reference)

The second method I described works great… until you go to put it into practice. It’s clearly not an impossible situation, but it’s pretty unlikely that you’ll write event handlers within an object that don’t use any of that object’s state (or even other methods on the object). Again, not impossible but just not the common use case. And since it’s not the common use case, you need to be concerned with the potentially problematic common use case 🙂

Let’s consider two classes (yes, again, two classes). We’ll use the first class I described above in both examples that has an event that we can hook onto, and a second class that looks similar to the class I introduced in the second example:

private class HookWithAnonymousDelegate2
{
    public HookWithAnonymousDelegate2(ObjectWithEvent objectWithEvent)
    {
        objectWithEvent.Event += (sender, args) =>
        {
            // handle your event and use something that's part of this instance
            SomeInnocentLittleMethod();
        };
    }

    ~HookWithAnonymousDelegate2()
    {
        Console.WriteLine(this + " is being finalized.");
    }

    private void SomeInnocentLittleMethod()
    {
        Console.WriteLine("... Not so innocent after all!");
    }
}

See the difference compared to example 2? The event handler in this class calls an instance method. This would be a pretty common thing to do (unless you like to duplicate all of your code and not use methods ever :P) and it doesn’t look like it should cause problems. And really, it won’t if you understand the implications of hooking an event handler up to an event. So once you’re done handling your events, make sure you clean up and remove your handlers!

In my opinion, the really interesting part of this example is that the event handler is only calling an instance method. It’s not even using any variables or properties of the instance. Still, the .NET framework is going to hold onto this second instance until we unhook.

Summary

Well, hopefully I haven’t scared you away from using events. The take-away point here is that you need to be mindful of hooking up your events and when/where you unhook them. Personally, unless you always plan to have two objects exist for the same lifetime, I wouldn’t hook up events in the constructors like I’ve done in my examples. Some closing tips:

  • Try only hooking onto events when you need to. If you don’t need to hook up all your events when initializing something, then don’t!
  • Be mindful of how you’re going to clean up your event hooking. Whenever you add an event handler, try to think of where you’ll be cleaning it up.
  • Hooking events onto singletons or global instances can make this problem a lot worse. Since your singleton will be around for the lifetime of your application, if you forget to unhook from your event then you’ll start accumulating a lot of garbage.

I’ve written up a little sample application that uses the example classes and walks you through the three examples I’ve outlined. All of them involve instantiating the classes, hooking up the events, and then how they behave differently when you try to clean them up. You can grab the source code from:

Hope you enjoyed! Remember to follow Dev Leader:


Dependency Injected Singletons… What?

Background

Previously I wrote a bit about singletons. I’m not afraid to say that I think singletons have a time and a place… Okay, I’m afraid to say it, but it’s actually how I feel 🙂 After learning more and more about inversion of control design patterns and programming by interfaces, I started to notice just how inflexible singletons are. When you consider using a singleton, you should be considering both the pros and cons without jumping right into it. Here’s an example of my approach for mixing singletons, programming by interfaces, and a bit of inversion of control.

The Setup

I’m actually surprised you got this far. I’m sure you’re probably just sticking around to see how messed up this could possibly be. I’m actually proud that this little pattern has worked out so well when I’ve used it, so it can’t possibly be that bad.

One major drawback to singletons is that they are often implemented as concrete classes. That is, you ask some class X for it’s instance (via a static property/method) and it provides you it. This doesn’t mix very well with programming by interfaces. So, the first step is to have your singleton return an interface instead of a concrete class. Unfortunately, this on it’s own only provides a few benefits, and it’s really only a minor abstraction layer. You can change your singleton class around all you want, but the only dependencies people are going to see are what’s exposed on the interface. As long as your interface isn’t changing, you’re in a good position. With this change alone, we’ve managed to tackle a bit on programming by interfaces, which makes me just a bit happier.

So, what’s the problem now then? Well, now that I have my singleton returning an interface, the unfortunate truth is it’s always going to be the same class backing that interface. It’s incredibly risky if I start putting some sort of logic in my singleton’s property to get the instance that will return different references that could implement the interface. I mean, once your code is running, you want to make sure you’re always getting the same reference back… or else you’re not using a singleton! The drawback to this is that it completely ruins inversion of control and dependency injection!

 

An Example

Consider that I have a singleton that has information about my application. (If you don’t like my example, then you’ll surely hate using WinForms, because Microsoft does it with their Application class. So, it’s a fair example!) Okay, so if we pretend that we need something just like the Application class in our project, we might create some interface IApplication and create a singleton that returns an instance of an IApplication.

Suppose in one implementation we have, we really want to be using reflection and the assembly information to figure out our application’s information. Our concrete class would implement the IApplication interface but the methods would revolve around using reflection and querying the assembly for what it wants. If we built up a whole framework that used this singleton… We’d be tied to that implementation!

What happens if we go to make another application that wants to use this same framework, but it needs to be able to provide the application information through a configuration file? Well… We’d be pooched! Our singleton that’s used everywhere (and yes, please continue crying about the use of the singleton… Just remember Microsoft’s Application class) and we can’t really do anything about it!

Or can we?

The “Solution”

Okay, so here we are. I’ve demonstrated the problem with a scenario that isn’t too far fetched. How do we fix this crappy situation we’ve got ourselves in by using the dreaded singleton pattern? We use my other best friend: events. Except we use them in a way that makes me cringe. Static events.

Here’s my solution the the above problem:

The Interface:

    public interface IApplication
    {
        string Name { get; }

        string Version { get; }
    }

The Singleton:

    public static class Application
    {
        private static readonly object _instanceLock = new object();
        private static IApplication _instance;

        public static event EventHandler<QueryTypeEventArgs> QueryType;

        public static IApplication Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_instanceLock)
                    {
                        if (_instance == null)
                        {
                            _instance = CreateInstance();
                        }
                    }
                }

                return _instance;
            }
        }

        private static IApplication CreateInstance()
        {
            var handler = QueryType;
            if (handler == null)
            {
                throw new InvalidOperationException(
                    "Cannot create an instance because the QueryType event " +
                    "handler was never set.");
            }

            var args = new QueryTypeEventArgs();
            handler.Invoke(null, args);

            if (args.Type == null)
            {
                throw new InvalidOperationException(
                    "Cannot create an instance because the type has not been " +
                    "provided.");
            }

            // NOTE: here's where things get weird. you need to define your own
            // sort of "contract" for what type of constructor you will allow.
            // you might not even use a constructor here... but you need to
            // define what mechanism the provided type must have to provide
            // you with a singleton instance. i'm a fan of providing a type
            // with a private parameterless constructor, so i'll demonstrate
            // with that. your requirements will change what this section of
            // code looks like.
            if (!typeof(IApplication).IsAssignableFrom(args.Type))
            {
                throw new InvalidOperationException(
                    "Cannot create an instance because the provided type does " +
                    "not implement the IApplication interface.");
            }

            const BindingFlags FLAGS = 
                BindingFlags.CreateInstance | 
                BindingFlags.Instance | 
                BindingFlags.NonPublic;

            var constructors = args.Type.GetConstructors(FLAGS);
            if (constructors.Length != 1)
            {
                throw new InvalidOperationException(
                    "Cannot create an instance because a single private " +
                    "parameterless constructor was expected.");
            }

            return (IApplication)constructors[0].Invoke(null);
        }
    }

The Program (With two types to inject!)

    internal class Program
    {
        private static void Main(string[] args)
        {
            Application.QueryType += (sender, e) =>
            {
                e.Type = typeof(ApplicationB);
            };

            Console.WriteLine(string.Format(
                "Application Name: {0}rnVersion: {1}",
                Application.Instance.Name,
                Application.Instance.Version));

            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }
    }

    internal class ApplicationA : IApplication
    {
        private ApplicationA()
        {
        }

        public string Name
        {
            get
            {
                return "Application A (Pretend this was from the assembly info)";
            }
        }

        public string Version
        {
            get { return "1234"; }
        }
    }

    internal class ApplicationB : IApplication
    {
        private ApplicationB()
        {
        }

        public string Name
        {
            get
            {
                return "Application B (Pretend this was from an XML file)";
            }
        }

        public string Version
        {
            get { return "9876"; }
        }
    }

So, if you were to run the program, what outputs would you expect in either case? What happens when you forget to set your event handler? What happens when you set your event handler and don’t provide a type? What if it’s a bad type?

 

Summary


I’m not claiming this is the best approach to solve this problem, and I’m not even encouraging that everyone go ahead and use it. Some of the pros of this are:

  • Advantages of programming by interfaces! You’re only exposing interface definitions to others.
  • Dependency injection capabilities. Inject your “singleton” into other applications.
  • All the goodies related to singletons
  • Easy to use. Just hook up your type to a event handler when your program initializes.

Some of the cons are:

  • All the things people hate about singletons. All of them.
  • Static events are absolutely hideous.
  • You’re giving some other class control of creating your singleton instance.
  • There is no compile time checking or contracts for how your singleton needs to be created.

And now that you know some of the good and some of the bad, can you leverage a design like this? You can check out a working solution I put together for the code and example I described above over at Google Code. Hope you were able to learn something (either good or bad)!


  • Nick Cosentino

    Nick Cosentino

    I work as a team lead of software engineering at Magnet Forensics (http://www.magnetforensics.com). I'm into powerlifting, bodybuilding, and blogging about leadership/development topics over at http://www.devleader.ca.

    Verified Services

    View Full Profile →

  • Copyright © 1996-2010 Dev Leader. All rights reserved.
    Jarrah theme by Templates Next | Powered by WordPress