.NET: How does the EventHandler race-condition fix work?

前端 未结 3 601
生来不讨喜
生来不讨喜 2021-02-08 04:24

There\'s the following pattern which is used to avoid a race condition when raising events in case another thread unsubscribes from MyEvent, making it null.

clas         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-08 05:22

    I would like to point out that comparing this incident to the 'int' case is probably inherently wrong since even though 'int' is atomic, it is a value type.

    But I think we've solved the case:

    Combining operations, such as Combine and Remove, do not alter existing delegates. Instead, such an operation returns a new delegate that contains the results of the operation, an unchanged delegate, or null. A combining operation returns null when the result of the operation is a delegate that does not reference at least one method. A combining operation returns an unchanged delegate when the requested operation has no effect.

    Delegate.CombineImpl Method shows the implementation.

    I looked over the implementation of Delegate and MulticastDelegate in the .NET 4 source code. Neither of them declare the += or -= operator. Coming to think of it, in Visual Basic.NET you don't even have them, you use AddHandler, etc...

    This means that the C# compiler implements this functionality and that the type doesn't really have anything to do with defining specialized operators.

    So this leads me to a logical conclusion which is, when you do:

    EventHandler handler = MyEvent;
    

    the C# compiler translates it to

    EventHandler handler = EventHandler.Combine(MyEvent)
    

    I'm surprised how quickly this question was solved thanks to your help.

    Thank you very much indeed!

提交回复
热议问题