我应该锁定“事件”吗? [英] should I lock 'event'?
问题描述
事件foo;
线程A:将调用foo + = handler;
线程B:将调用foo - = handler;
我应该锁定foo吗?
锁定 foo
是一个坏主意,因为该值将每次都改变您应该锁定不更改的变量:
private readonly object eventLock = new object ();
私人EventHandler fooHandler;
公共事件EventHandler Foo
{
添加
{
锁(eventLock)
{
fooHandler + = value;
}
}
删除
{
lock(eventLock)
{
fooHandler - = value;
}
}
}
private void OnFoo(EventArgs e)
{
EventHandler handler;
lock(eventLock)
{
handler = fooHandler;
}
if(handler!= null)
{
handler(this,e);
}
}
请注意,如果您使用类似字段的事件,像这样:
公共事件EventHandler Foo;
然后你会自动获得一个锁定(这个)添加/删除,在调用处理程序之前,必须手动添加它(假设你想确保你读取最近写的值)。个人而言,我不是锁定这个的粉丝,但你可能不介意 - 这肯定会使更简单的代码。
should I lock event in the following case:
event foo;
thread A: will call foo += handler;
thread B: will call foo -= handler;
should I lock foo?
Locking on foo
is a bad idea, because the value will change each time. You should lock on a variable which doesn't change:
private readonly object eventLock = new object();
private EventHandler fooHandler;
public event EventHandler Foo
{
add
{
lock (eventLock)
{
fooHandler += value;
}
}
remove
{
lock (eventLock)
{
fooHandler -= value;
}
}
}
private void OnFoo(EventArgs e)
{
EventHandler handler;
lock (eventLock)
{
handler = fooHandler;
}
if (handler != null)
{
handler(this, e);
}
}
Note that if you use a field-like event, like this:
public event EventHandler Foo;
then you'll automatically get a "lock(this)" on add/remove, although you'd have to manually add it when fetching the handler before calling it (assuming you want to make sure you read the most recently written value). Personally I'm not a fan of locking on "this", but you may not mind - and it certainly makes for simpler code.
这篇关于我应该锁定“事件”吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!