dotnetdev dotnetdev - 1 year ago 86
C# Question

Use of null check in event handler

When checking if an event handler is null, is this done on a per-thread basis?

Ensuring someone is listening to the event is done like this:

EventSeven += new DivBySevenHandler(dbsl.ShowOnScreen);

If I add code following this pattern above where I check for null, then why would I need a null check (code taken from this site). What am I missing?

Also, what's the rule with events and GC?

Answer Source

It's really not clear what you mean I'm afraid, but if there's the possibility of the delegate being null, you need to check that separately on each thread. Typically you'd do:

public void OnSeven()
    DivBySevenHandler handler = EventSeven;
    if (handler != null)

This ensures that even if EventSeven changes during the course of OnSeven() you won't get a NullReferenceException.

But you're right that you don't need the null check if you've definitely got a subscribed handler. This can easily be done in C# 2 with a "no-op" handler:

public event DivBySevenHandler EventSeven = delegate {};

On the other hand, you might want some sort of locking just to make sure that you've got the "latest" set of handlers, if you might get subscriptions from various threads. I have an example in my threading tutorial which can help - although usually I'd recommend trying to avoid requiring it.

In terms of garbage collection, the event publisher ends up with a reference to the event subscriber (i.e. the target of the handler). This is only a problem if the publisher is meant to live longer than the subscriber.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download