class Plane
{
public event EventHandler Land;
protected void OnLand()
{
if ( null != Land )
{
Land( this, null );
}
}
}
it is event handler best practice to do instea开发者_开发技巧d:
EventHandler temp = Land;
if ( null != temp )
{
temp( this, null );
}
Is that truly necessary? In what case could temp be different from Land?
In the case of multi-threaded access, I believe. If you don't cache the reference, another thread can null it out after your guard but before you fire.
If you have concurrency with many threads modifying Land
.
When in between the test and the raise the last handler is removed from the list by an other thread.
the invokation list of the event will be copied when it changes and the temp reference will still hold the original list.
See: C# Events and Thread Safety
精彩评论