How to unsubscribe from an event which uses a lambda expression?

前端 未结 3 1256
傲寒
傲寒 2020-11-29 09:06

I have the following code to let the GUI respond to a change in the collection.

myObservableCollection.CollectionChanged += ((sender, e) => UpdateMyUI());         


        
3条回答
  •  失恋的感觉
    2020-11-29 09:39

    It's an ok way to go, unless myObservableCollection is going to live longer than 'this', in which case you could end up with a memory leak, as the delegate which is created behind the scenes will conserve a reference to your 'this', which will keep it alive. If you are repeatedly creating and 'destroying' whatever is listening to the event, you will find that they aren't being collected by the garbage collector.

    If this is a problem, you can go the route suggested in the answers, conserving a reference to the handler, which you must create first.

    Another solution is to use weak references to create an event handler which will allow the subscriber to be collected if there are not other references. I've explored this solution in this question and answer.

提交回复
热议问题