views:

325

answers:

3

Following on from this post - what are the disadvantages when using the -= then += approach suggested when I only ever want one handler event to fire?

_value.PropertyChanged -= _handlerMethod;
_value.PropertyChanged += _handlerMethod;
+4  A: 

This doesn't guarantee that there is only one handler fired.

Another location could, potentially, subscribe your handler to your event multiple times. In this case, you will only remove the first handler call.

By inspecting the invocation list of the event, you could guarantee this behavior, if you truly only want a single handler to be subscribed at a time.

Reed Copsey
As a side note, these two lines also would not impact any other handlers which had been added. I believe the only impact of these two statements is the possible reordering of the attached handlers.
cdkMoose
Exactly. You'll just guarantee that you have a _handlerMethod at the end of the invocation list (although ordering is not guaranteed by spec), not that there are no other instances in there.
Reed Copsey
How do you inspect the invocation list at runtime (c#)?
Mark Cooper
See the first answer in the post you referenced. Basically, you use Delegate.GetInvocationList() to get an array of delegates (which are the methods being called). You can then check them directly. You can also override the add/remove handlers for the event to guarantee a single method instance (either no more than one total, or one per delegate, etc). See: http://msdn.microsoft.com/en-us/library/system.delegate.getinvocationlist.aspx
Reed Copsey
+1  A: 

The idea here is that the -= operator is not going to do anything if your event handler is not assigned.

I don't personally like this approach, I think you should really aim to refactor your code so that you know that the event handler is assigned only once.

The disadvantages would be: - possibility of race condition, if your app is multithreaded and the event gets fired when the handler is not assigned - I am also not sure what happens when you run _value.PropertyChanged -= _handlerMethod when two copies of the handler are already assigned. - messy code - obviously its not clear from the code which class and when is listening to the event

Grzenio
+2  A: 

If you really want only one handler to execute, then you may want to use a settable property of the appropriate delegate type instead of an event. Only one delegate will be stored; you can execute the delegate the same as you would the event handler.

CodeSavvyGeek