【问题标题】:Thread Safe Event Handling [duplicate]线程安全事件处理 [重复]
【发布时间】:2011-10-11 12:05:45
【问题描述】:

可能重复:
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 如何使其成为线程安全的。谁能解释一下?

【问题讨论】:

标签: c#


【解决方案1】:

如果是的话

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

mNotification 可以被if (mNotification!=null)mNotification(this, null); 之间的另一个线程设置为空

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多