Domanda

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?

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top