C#:初始化事件处理程序与虚拟 [英] C#: Initializing an event handler with a dummy
问题描述
我见过这种代码一些地方:
I've seen this sort of code some places:
public event SomeEventHandler SomeEvent = (s, e) => { };
是一个做事的推荐的方式?这是什么解决的,它有任何值得注意的副作用吗?请问我还要做null检查?或者是,正是我不必做任何更多? ?将垃圾收集还是因为它应该工作
Is that a recommended way of doing things? What does it solve, and does it have any noteworthy side effects? Will I still have to do null checks? Or is that exactly what I don't have to do any more? Will garbage collection still work as it should?
例如:
private PropertyChangedEventHandler propertyChanged;
private readonly object propertyChangedLock = new object();
public event PropertyChangedEventHandler PropertyChanged
{
add
{
lock (propertyChangedLock)
propertyChanged += value;
}
remove
{
lock (propertyChanged)
propertyChanged -= value;
}
}
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler;
lock (propertyChangedLock)
handler = propertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
我能改第一行成这样:
Could I change the first line into this:
private PropertyChangedEventHandler propertyChanged = (s, e) => { };
然后跳过OnPropertyChanged方法空检查?如果我再跳过空支票可能我随后也跳了锁?如果是这样,会给我这样的:
And then skip the null-check in the OnPropertyChanged method? And if I then skip the null-check could I then also skip the lock? If so that would give me this:
protected void OnPropertyChanged(string propertyName)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
请问服用初始化到时是安全的?还是有一些副作用,我错过了什么?
Would that be safe when taking the initialization into account? Or are there some side effects I have missed?
推荐答案
尽管你不需要做无效的检查,如果你真的要尽量使事件线程安全的,你还需要将其锁获取:
While you don't need to do the nullity checks, if you really want to try to make the event thread-safe, you still need to fetch it in a lock:
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler;
lock (propertyChangedLock)
{
handler = propertyChanged;
}
handler(this, new PropertyChangedEventArgs(propertyName));
}
否则,你可能没有获取最新的价值 - 如果事件处理程序正在在不同的线程增加,理论上可以引发事件永远永远不会调用新的处理程序。在实践中,我相信你会几乎总是跑不掉而不锁,但在内存模型项你应该有部分的排序围栏。
我个人建议你不要的尝试的使事件线程安全的。
Personally I recommend that you don't try to make the events thread-safe.
这篇关于C#:初始化事件处理程序与虚拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!