可能重复:
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
如何使其成为线程安全的。有人可以解释一下吗?
答案 0 :(得分:3)
如果是
if (mNotification!=null)
{
mNotification(this, null);
}
在if (mNotification!=null)
和mNotification(this, null);
答案 1 :(得分:1)
它的作用是在特定时刻制作对原始事件的引用的副本,以便如果在null检查之后随后使用它,则它将指向不评估为null的引用。如果未使用此模式,则可以进行检查,如果它不为null,则可以在另一个线程上取消订阅所有处理程序,然后在调用该事件时该事件将为null。复制原始引用可消除此潜在的线程问题。