A Developer WeBLOG RSS 2.0

Be very carefull if you have code like the above example. It may seems ok, because you unregister the event handler at the start of the function, you reregister it again at the end of the function. No event get lost, no drama! Now let say, in that function we add another function called foo. In foo we add the same event handler logic, that is unregistering and re-registering the handler.

The above code has a subtle bug, which is the event handler get registered twice. One time at the end of Foo and the other at the end of Form1_Load function. The impact of this obviously when the event get raised, the handler will be called twice. Okay it may not be very subtle in the above code, but if you have a more complicated function, it's rather hard to track down this bug. It happened to me recently on one of our product code base. What I did to ensure this kind of problem never happens again is to add another function that's responsible in adding the handler to the event. This function will be used always for adding the handler to the event. The code is as below.

UPDATE: A better and more flexible approach can be found here

RWendi

Tuesday, January 20, 2009 10:40:51 AM UTC |  Comments [0]
.NET | c# | Programming
All Content © 2010, RWendi