Question

Here is the example code: http://msdn.microsoft.com/en-us/library/system.eventhandler.aspx

protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
{
    EventHandler<ThresholdReachedEventArgs> handler = ThresholdReached;

    if (handler != null)
    {
        handler(this, e);
    }
}

Couldn't we just check if the ThresholdReached is null directly?

Was it helpful?

Solution

Yes, you could just check null directly.

This style of coding helps with multithreading issues. If you check if ThresholdReached is null, and then another thread makes it null, and then you try to run the handler, it will fail. Not likely, but possible if you are running several threads.

So in this example, you get the value of ThresholdReached first, so that you can check for null and call it without the fear of other threads messing with that value between the two calls. If you don't have multi-threading concerns, then by all means, go ahead and check null directly.

You'll find this kind of defensive coding in all sorts of scenarios where multithreading is an issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top