Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

c# - Add delegate to event - thread safety

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

and a remove handler that looks the same but with Delegate.Remove instead of Delegate.Combine.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...