Possible memory-leak on a self-removable event handler A friend of mine asked me a question recently. He was needed to subscribe to an event of some object (window button click) and unsubscribe from it on a first call of a handler. Also he noticed that object is dynamically created and his handler is a delegate.

After some thinking I came up with a solution using closures of an object and a delegate itself:

class Program
{
    class A
    {
        public event EventHandler OnRaise;

        public void RaiseEvent(string text)
        {
            Console.WriteLine("a said: " + text);
            if (OnRaise != null)
                OnRaise(this, null);
        }
    }

    static void Main(string[] args)
    {
        var a = new A();

        EventHandler handler = null;
        handler = (x, y) =&gt;
            {
                Console.WriteLine("handler's working");
                a.OnRaise -= handler;
            };

        a.OnRaise += handler;

        a.RaiseEvent("blah blah ");
        a.RaiseEvent("beep beep ");

        handler = null;
        a = null;

        GC.Collect();

        Console.ReadKey();
    }
}


It does all requested behavior but I'm not sure if it's good and safe from memory-leaks. It would be great if anyone can review the code and help with advice or offer a better way to solve the problem.
The code that you have will not result in holding onto a reference to any variables that the anonymous handler closes over once that handler is fired and the handler variable leaves scope or is set to something else (i.e. null), even if the A instance is kept alive.

So in short, it's fine.

Note that this is only ever a problem in the first place if the anonymous even handler closes over a variable that is a) expensive to keep alive, i.e. a very large collection of data and b) has a much shorter lifetime than the object that has the event being subscribed to.  If the object holding the event goes out of scope before, or very soon after, whatever is being closed over, then the object is not held in memory any longer than if the event handler is unsubscribed.  That specific case isn't actually all that common.