Why is the standard C# event invocation pattern thread-safe without a memory barrier or cache invalidation? What about similar code?

后端 未结 5 1797
余生分开走
余生分开走 2021-02-19 03:37

In C#, this is the standard code for invoking an event in a thread-safe way:

var handler = SomethingHappened;
if(handler != null)
    handler(this, e);
         


        
5条回答
  •  庸人自扰
    2021-02-19 04:28

    It seems to me you should be using see this article in this case. This ensures the compiler doesn't perform optimisations that assume access by a single thread.

    Events used to use locks, but as of C# 4 use lock-free synchronisation - I'm not sure exactly what (see this article).

    EDIT: The Interlocked methods use memory barriers which will ensure all threads read the updated value (on any sane system). So long as you perform all updates with Interlocked you can safely read the value from any thread without a memory barrier. This is the pattern used in the System.Collections.Concurrent classes.

提交回复
热议问题