Question

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

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

First of all is this a good way to do this?

Second: what's the code to unsubscribe from this event? Is it the same but with -= (and then the complete anonymous method again)?

Was it helpful?

Solution

If you need to unsubscribe from an event, you need an instanced reference. Unfortunately, that means you can't use that particular syntax.

OTHER TIPS

First of all... yes its a good way of doing it, it's clean, small form and easy to read & understand... the caveat of course is "Unless you later want to unsubscribe".

I believe Jon Skeet pointed out before that "the specification explicitly doesn't guarantee the behaviour either way when it comes to equivalence of delegates created with anonymous methods."

So if you need to unsubscribe from the event at a later time, you'd be best to actually create a delegate instance so you can hang onto the reference for later.

var myDelegate = delegate(sender, e){UpdateMyUI()};

myObservableCollection.CollectionChanged += myDelegate;

myObservableCollection.CollectionChanged -= myDelegate;

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top