开发者

Thread Safe Event Handling [duplicate]

This question already has answers here: 开发者_Go百科 Closed 11 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜