可能重复:
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如何使其线程安全。有人能解释一下吗?
发布于 2011-10-11 12:10:29
如果是
if (mNotification!=null)
{
mNotification(this, null);
}mNotification可以通过if (mNotification!=null)和mNotification(this, null);之间的另一个线程设置为null。
发布于 2011-10-11 12:12:38
它所做的是在特定时刻复制对原始事件的引用,以便如果它随后在空检查之后使用,它将指向不计算为null的引用。如果不使用此模式,则可以检查它是否为空,所有处理程序都可以在另一个线程上取消订阅,那么在调用该事件时事件将为空。复制原始引用消除了这个潜在的线程问题。
https://stackoverflow.com/questions/7725766
复制相似问题