[英]How to Explicit event accessors
Here is a sketch of explicit event assessors: 以下是明确的事件评估员的草图:
delegate void EventHandler (SomeObject m, EventArgs e);
EventHandler _priceChanged; //Private Delegate
public event EventHandler PriceChanged
{
add {_priceChanged += value;}
remove {_priceChanged -= value;}
}
Apparently the difference between this and the standard implementation is that the use of the delegate is not thread-safe. 显然,这与标准实现之间的区别在于委托的使用不是线程安全的。 How do I make this thread-safe? 如何使这个线程安全?
How do I allow things like : 我如何允许以下内容:
if (PriceChanged != null)... etc
Try this: 尝试这个:
delegate void EventHandler (SomeObject m, EventArgs e);
EventHandler _priceChanged; //Private Delegate
private Object _myLock = new Object();
public event EventHandler PriceChanged
{
add {
lock(_myLock)
{_priceChanged += value;}
}
remove {
lock(_myLock)
{_priceChanged -= value;}
}
}
- Apparently the difference between this and the standard implementation is that the use of the delegate is not thread-safe. 显然,这与标准实现之间的区别在于委托的使用不是线程安全的。 How do I make this thread-safe? 如何使这个线程安全?
Refer to Shai's answer. 请参考Shai的回答。
- How do I allow things like : 我如何允许以下内容:
if (PriceChanged != null)... etc
You can't, not on the eventhandler declaration level - this always needs to be done in the code calling this. 你不能,不是在事件处理器声明级别 - 这总是需要在调用它的代码中完成。 Just to give an example: one reason for _priceChanged
to be null is if neither add nor remove was ever called - how could they prevent the null exception then? 举一个例子: _priceChanged
为null的一个原因是,如果既没有调用也没有删除 - 那么它们怎么能阻止null异常呢? Unless you want to initialize your delegate collection with a dummy callback, but that's just evil. 除非你想用虚拟回调初始化你的委托集合,但这只是邪恶的。
Have a look at reactive extensions if you want an alternative. 如果您想要替代方案,请查看被动扩展 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.