Questions and answers about events and threads
This pertains to Item 22, and Item 45.

Question 1:

Can you further explain the idiom you recommend on top of page 133 (see below) to raise an event. Specifically, how does making a copy of the reference provide protection?

// add a message, and log it.
public void AddMsg ( int priority, string msg )
{
  // This idiom discussed below.
  AddMessageEventHandler l = Log;
  if ( l != null )
    l ( null, new LoggerEventArgs( priority, msg ) );
  }

In my mind a "copy of a reference" is, well, just a copy-of-a-reference, which would not prevent the referenced object from being changed elsewhere. I would agree that a copy of the underlying _object_ would provide protection, but that doesn't seem to be what's going on here.

Answer 1:

This idiom does work because of the behavior of the Add and Remove accessors for an event. If another thread calls Remove(), that does not modify the invocation list you’ve copied to the local variable ‘l’. Rather, it creates a new invocation list with no targets. Your invocation list is still valid. You are not making a deep copy of the invocation list, but any other thread the modifies your invocation list does.

Question 2:

Also while on this topic, do you recommend protecting the actual event call with a Try/Catch as a way to protect against exception-throwing event handlers (that others might write, of course)? Not sure that there would be anything to do in the Catch, maybe just Catch {}. Interested to know what you think.

Answer 2:

It varies. I believe that event handlers should never throw exceptions. (See Item 45, p. 270). However, I don’t believe that you can always count on others to follow that rule. If you are creating libraries that will be used by a large audience, you should be very defensive and wrap event handler invocations with try / catch. When you are creating closed systems, and you can ensure that none of the event handlers could possibly throw exceptions, I find that the simpler syntax easier to read and maintain.



Published Monday, February 14, 2005 6:22 AM by wwagner
Filed under: ,

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)