C# Events and Thread Safety

前端 未结 15 1312
甜味超标
甜味超标 2020-11-22 06:00

UPDATE

As of C# 6, the answer to this question is:

SomeEvent?.Invoke(this, e);

I frequently hear/read the fo

15条回答
  •  一整个雨季
    2020-11-22 06:22

    Please take a look here: http://www.danielfortunov.com/software/%24daniel_fortunovs_adventures_in_software_development/2009/04/23/net_event_invocation_thread_safety This is the correct solution and should always be used instead of all other workarounds.

    “You can ensure that the internal invocation list always has at least one member by initializing it with a do-nothing anonymous method. Because no external party can have a reference to the anonymous method, no external party can remove the method, so the delegate will never be null” — Programming .NET Components, 2nd Edition, by Juval Löwy

    public static event EventHandler PreInitializedEvent = delegate { };  
    
    public static void OnPreInitializedEvent(EventArgs e)  
    {  
        // No check required - event will never be null because  
        // we have subscribed an empty anonymous delegate which  
        // can never be unsubscribed. (But causes some overhead.)  
        PreInitializedEvent(null, e);  
    }  
    

提交回复
热议问题