0

I have an interface that declares an event that will be raised when properties are changed in the inheriting class. I was reading about correct event calling ex:

var eventptr = MyEvent;
if(eventptr != null)
    MyEvent(args);

When I came across : ' in rare cases a delegate can detach' and when it's called it would throw a null reference exception. I was thinking about adding a static function(probably an extension method) that all classes that inherited the interface could call. The function would accept the arguments and the invocation list of the event, it would cycle through each event and if an exception was thrown it would continue down the invocation list which is critical that it does. Can the static function still invoke the delegates in the invocation list even though the function is not part of the base class? Also are there any better ideas to what I'm trying to prevent?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • "in rare cases a delegate can detach" - Where did you read that? – p.s.w.g Jan 02 '14 at 06:51
  • @p.s.w.g I don't know the link anymore here is a similar one [link]http://blogs.msdn.com/b/ericlippert/archive/2009/04/29/events-and-races.aspx – IBreakThingsElegantly Jan 02 '14 at 07:07
  • Delegates are immutable, `eventptr` will be a copy, not a reference to, of `MyEvent`. You do not need to worry about the `eventptr` delegate changing. – William Jan 02 '14 at 07:39
  • @William I know that much, I'm referring to the delegate list of eventptr, and one of the delegates in that list referring to a null object. It's a very rare case – IBreakThingsElegantly Jan 02 '14 at 08:01
  • The `eventptr` will not contain a `null` delegate reference. Ever. The blog entry that you reference is discussing a race condition that occurs if you do not use a temporary variable. Without the temporary variable `MyEvent` may become `null` between checking that it is not `null` and attempting to call it. The remainder of the article is covering the possibility that an event handler may be called even after it has removed itself from the multicast delegate. The event handler is responsible for ignoring the event in that case. – William Jan 03 '14 at 06:23

0 Answers0