线程安全事件处理

时间:2011-10-11 12:05:46

标签: c#

  

可能重复:
  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);
    }
}

复制mNotification如何使其成为线程安全的。有人可以解释一下吗?

2 个答案:

答案 0 :(得分:3)

如果是

if (mNotification!=null)
{
    mNotification(this, null);
}

if (mNotification!=null)mNotification(this, null);

之间的另一个帖子可以将mNotification设置为null

答案 1 :(得分:1)

它的作用是在特定时刻制作对原始事件的引用的副本,以便如果在null检查之后随后使用它,则它将指向不评估为null的引用。如果未使用此模式,则可以进行检查,如果它不为null,则可以在另一个线程上取消订阅所有处理程序,然后在调用该事件时该事件将为null。复制原始引​​用可消除此潜在的线程问题。