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

前端 未结 3 599
生来不讨喜
生来不讨喜 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:02

    I would expect that once I got the MyEvent delegate inside the 'handler' reference, once somebody would change MyEvent that the object that 'handler' references will be changed as well. [..] Notice that System.Delegate is a class and not a struct.

    Although you are correct that delegate-types are references-types, they are immutable reference-types. From System.Delegate:

    "Delegates are immutable; once created, the invocation list of a delegate does not change.[...] 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 Nothing.


    On another note, the only issue this pattern addresses is preventing the attempted invocation of a null delegate-reference. Events are prone to races despite this "fix".

提交回复
热议问题