Event handlers invocation in EntLib

Topics: General discussion
Jun 9, 2008 at 10:58 AM
Hi.
I've found such code (class LoggingInstrumentationProvider):

    public class LoggingInstrumentationProvider
    {
        [InstrumentationProvider("TraceListenerEntryWritten")]
        public event EventHandler<EventArgs> traceListenerEntryWritten;

        public void FireTraceListenerEntryWrittenEvent()
        {
            if (traceListenerEntryWritten != null) traceListenerEntryWritten(this, new EventArgs());
        }
}

I guess it's not very good code. We should copy event-field into local variable before invocation. That should be done to prevent NullReferenceException if someone removes a handler after we check against null but before we invoke a handler. Probability is low, but exists.
Jun 9, 2008 at 10:03 PM
Guess it should look like this, I included using the EventArgs.Emtpy instead of creating a new object (help the GC out).

    public class LoggingInstrumentationProvider
    {
        [InstrumentationProvider("TraceListenerEntryWritten")]
        public event EventHandler<EventArgs> traceListenerEntryWritten;

        public void FireTraceListenerEntryWrittenEvent()
        {
            EventHandler<EventArgs> handler = traceListenerEntryWritten;
            if (handler != null) handler (this, EventArgs.Empty);
        }
}

EvilShrike wrote:
Hi.
I've found such code (class LoggingInstrumentationProvider):

    public class LoggingInstrumentationProvider
    {
        [InstrumentationProvider("TraceListenerEntryWritten")]
        public event EventHandler<EventArgs> traceListenerEntryWritten;

        public void FireTraceListenerEntryWrittenEvent()
        {
            if (traceListenerEntryWritten != null) traceListenerEntryWritten(this, new EventArgs());
        }
}

I guess it's not very good code. We should copy event-field into local variable before invocation. That should be done to prevent NullReferenceException if someone removes a handler after we check against null but before we invoke a handler. Probability is low, but exists.


Jun 10, 2008 at 9:15 AM
Yes, exactly.
EntLib constaints a number of such lacks of consistency. It'd be nice to hear EntLib's guys to say something promising about fixing ;)