Alex Rivera | Logout

Preventing same Event handler assignment multiple times

Asked 2008-12-30T06:31:21.163
50

If I am assigning an event handler at runtime and it is in a spot that can be called multiple times, what is the recommended practice to prevent multiple assignments of the same handler to the same event.

object.Event += MyFunction

Adding this in a spot that will be called more than once will execute the handler 'n' times (of course).

I have resorted to removing any previous handler before trying to add via

object.Event -= MyFunction; 

object.Event += MyFunction;

This works but seems off somehow. Any suggestions on proper handling ;) of this scenario.

Edit
Report

2 Answers

3

I tend to add an event handler in a path that's executed once, for example in a constructor.

answered 2008-12-30T06:40:26.247
0

What is the access modifier of 'object'?

If it's private, you only need to worry about the containing object setting the event handler. If it's internal, you only need to worry about the containing assembly setting the event handler. If it's public, then it's wide-open.

If 'object' can be made private on the containing class, you can make your checks much more efficient by controlling event handler assignment in the local class.

If 'internal' or 'public' and uniqueness is a requirement, go with a wrapper class that hides 'object' and instead exposes a method for assigning an event handler with your checks behind it to ensure uniqueness.

answered 2008-12-30T16:23:54.307

Your Answer