Thread Safe Event Handling [duplicate]
Possible Duplicate:
Checking for null before event dispatching… thread safe? Raise event thread safely - best practice
protected void NotificationEvent(Object sender, EventArgs e)
{
// Copy to a temporary variable to be thread-safe
EventHandler<EventArgs> tmp = mNotification;
if (tmp!= null)
{
tmp(this, null);
}
}
How does copying mNotification
makes it thread-safe. Can someone explain?
If it were
if (mNotification!=null)
{
mNotification(this, null);
}
mNotification could be set to null by another thread between if (mNotification!=null)
and mNotification(this, null);
What it does is to make a copy of the reference to the original event at that particular moment in time, so that if it is subsequently used after the null check, it will point to a reference that does not evaluate to null. If this pattern is not used, then a check can be made if it is not null, all handlers could be unsubscribed on another thread, then the event would be null by the time it was invoked. Copying the original reference removes this potential threading issue.
精彩评论