添加委托事件 - 线程安全 [英] Add delegate to event - thread safety
问题描述
有可能执行从多个线程同时下面code。
It is possible to execute the following code from multiple threads simultaneously.
this._sequencer.Completed += OnActivityFinished;
时的线程安全,以委托添加到从多个线程事件处理程序?
Is it thread safe to add delegate to an event handler from multiple threads?
时的线程安全,从事件处理程序中从多个线程删除委托?
Is it thread safe to remove delegate to from event handler from multiple threads?
什么是使这个线程安全的最简单和维护的方式?
What is the simplest and maintainable way of making this thread safe?
推荐答案
如果您没有指定自己的事件添加/删除处理,C#编译器生成此添加处理程序(由<一个重建HREF =http://www.red-gate.com/products/reflector/> .net反射):
If you don’t specify your own event add/remove handlers, the C# compiler generates this add handler (reconstructed by .NET Reflector):
public void add_MyEvent(EventHandler value)
{
EventHandler handler2;
EventHandler myEvent = this.MyEvent;
do
{
handler2 = myEvent;
EventHandler handler3 = (EventHandler) Delegate.Combine(handler2, value);
myEvent = Interlocked.CompareExchange<EventHandler>(ref this.MyEvent, handler3, handler2);
}
while (myEvent != handler2);
}
和,看起来删除处理程序相同,但与 Delegate.Remove
而不是 Delegate.Combine
。
and a remove handler that looks the same but with Delegate.Remove
instead of Delegate.Combine
.
注意使用 Interlocked.CompareExchange
的?这prevents更新事件的支持字段,并从中读取之间的竞争条件。因此,它是线程安全
Notice the use of Interlocked.CompareExchange
? This prevents a race condition between updating the event’s backing field and reading from it. Thus, it is thread-safe.
这篇关于添加委托事件 - 线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!