Garbage collection when using anonymous delegates for event handling

后端 未结 4 1766
灰色年华
灰色年华 2020-11-27 18:10

UPDATE

I have combined various answers from here into a \'definitive\' answer on a new question.

Original question

4条回答
  •  [愿得一人]
    2020-11-27 18:40

    If you retain a reference to the anonymous delegate and then remove it when the controls are removed from the form that should allow both the controls and the anonymous delegates to be garbage collected.

    So something like this:

    public static class Linker
    {
    
        //(Non-lambda version, I'm not comfortable with lambdas:)
        public static EventHandler> Link(Publisher publisher, Control subscriber)
        {
             EventHandler> handler = delegate(object sender, ValueEventArgs e)
                 {
                      subscriber.Enabled = e.Value;
                 };
             publisher.EnabledChanged += handler;
             return handler;
        }
    
        public static void UnLink(Publisher publisher, EventHandler> handler)
        {
            publisher.EnabledChanged -= handler;
        }
    
    }
    

    See Unsubscribe anonymous method in C# for an example of removing delegates.

提交回复
热议问题