C#:线程安全事件 [英] C#: Thread-safe events
问题描述
下面的实现是线程安全吗?如果不是我失踪了?我应该在哪里有 volatile
关键字?或者在 OnProcessingCompleted
方法中的某个位置锁定?如果是,在哪里?
Is the implementation below thread-safe? If not what am I missing? Should I have the volatile
keywords somewhere? Or a lock somewhere in the OnProcessingCompleted
method? If so, where?
public abstract class ProcessBase : IProcess
{
private readonly object completedEventLock = new object();
private event EventHandler<ProcessCompletedEventArgs> ProcessCompleted;
event EventHandler<ProcessCompletedEventArgs> IProcess.ProcessCompleted
{
add
{
lock (completedEventLock)
ProcessCompleted += value;
}
remove
{
lock (completedEventLock)
ProcessCompleted -= value;
}
}
protected void OnProcessingCompleted(ProcessCompletedEventArgs e)
{
EventHandler<ProcessCompletedEventArgs> handler = ProcessCompleted;
if (handler != null)
handler(this, e);
}
}
注意:我拥有私有事件和显式接口的原因是因为它是一个抽象的基类。而从它继承的类不应该直接对事件做任何事情。添加了类包装,以便它更清楚=)
Note: The reason why I have private event and explicit interface stuff, is because it is an abstract base class. And the classes that inherit from it shouldn't do anything with that event directly. Added the class wrapper so that it is more clear =)
推荐答案
不需要私人 ProcessCompleted
成为一个事件
- 它可能只是一个字段: private EventHandler< ProcessCompletedEventArgs> ProcessCompleted;
- 在类内部,它总是直接到字段,所以$ code>事件的东西丢失了。
There is no need for the private ProcessCompleted
member to be an event
- it could just be a field: private EventHandler<ProcessCompletedEventArgs> ProcessCompleted;
- inside the class it always goes straight to the field, so the event
stuff is lost anyway.
您使用显式锁定对象显示的方法不仅仅是具有类似场景的事件(即 public事件EventHandler< ProcessCompletedEventArgs> ProcessCompleted;
- 唯一的区别是你没有锁定this(这是一件好事 - 你应该 避免锁定这个
)..处理程序变量方法是正确的,但仍然有一个应该注意的副作用。
The approach you've shown with an explicit lock object isn't much more thread-safe than just having a field-like event (i.e. public event EventHandler<ProcessCompletedEventArgs> ProcessCompleted;
- the only difference is that you aren't locking "this" (which is a good thing - you should ideally avoid locking on this
).. The "handler variable" approach is the right one, but there are still side-effects you should be aware of.
这篇关于C#:线程安全事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!