This is a paranoia thing to do with threading. If another thread unsubscribes the last handler just after you've checked it for null
, it could become null
and you'll cause an exception. Since delegates are immutable, capturing a snapshot of the delegate into a variable stops this from happening.
Of course, it does have the other side effect that you could (instead) end up raising the event against an object that thinks it already unsubscribed...
But to stress - this is only an issue when multiple threads are subscribing / unsubscribing to the object, which is a: rare, and b: not exactly desirable.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…