C#语言的事件处理程序
class Plane
{
public event EventHandler Land;
protected void OnLand()
{
if ( null != Land )
{
Land( this, null );
}
}
}
这是事件处理程序的最佳实践:
EventHandler temp = Land;
if ( null != temp )
{
temp( this, null );
}
这真的有必要吗?在什么情况下 temp 可能与 Land 不同?
class Plane
{
public event EventHandler Land;
protected void OnLand()
{
if ( null != Land )
{
Land( this, null );
}
}
}
it is event handler best practice to do instead:
EventHandler temp = Land;
if ( null != temp )
{
temp( this, null );
}
Is that truly necessary? In what case could temp be different from Land?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在多线程访问的情况下,我相信。如果您不缓存引用,则另一个线程可以在您的防护之后但在您触发之前将其清空。
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.
如果您有许多线程并发修改
Land
。If you have concurrency with many threads modifying
Land
.在测试和引发之间,最后一个处理程序会被其他线程从列表中删除。
事件的调用列表在更改时将被复制,并且临时引用仍将保留原始列表。
请参阅:C# 事件和线程安全
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