Is C# 6 ?. (Elvis op) thread safe? If so, how?

前端 未结 2 1692
说谎
说谎 2020-12-01 17:45

Apologies in advance: this question comes from a hard-core, unreformed C++ developer trying to learn advanced C#. Consider the following:

if (myUserDefinedOb         


        
2条回答
  •  被撕碎了的回忆
    2020-12-01 18:41

    From MSDN (emphasis mine):

    Another use for the null-condition member access is invoking delegates in a thread-safe way with much less code. The old way requires code like the following:

    var handler = this.PropertyChanged;
    if (handler != null)
        handler(…)
    

    The new way is much simpler:

    PropertyChanged?.Invoke(e)
    

    The new way is thread-safe because the compiler generates code to evaluate PropertyChanged one time only, keeping the result in temporary variable.

    So there is no locking involved here - thread-safety is enforced by creating a local temporary variable, which prevents a different thread from modifying that variable in between the null check and some other operation.

提交回复
热议问题