Max*_*xim 4 c# multithreading c#-6.0
这两个样本是否相同?可以用Invoke和null传播替换旧式的提升吗?
旧:
public event EventHandler<MyEventArgs> MyEvent;
protected virtual void OnMyEvent(MyEventArgs args)
{
EventHandler<MyEventArgs> handler = this.MyEvent;
if (handler != null)
handler(this, args);
}
Run Code Online (Sandbox Code Playgroud)
新:
public event EventHandler<MyEventArgs> MyEvent;
protected virtual void OnMyEvent(MyEventArgs args)
{
this.MyEvent?.Invoke(this, args);
}
Run Code Online (Sandbox Code Playgroud)
空检查很重要但很明显.什么是附加变量?
null-propogation如何在内部工作?它是否对事件有线程安全性?
PS关于事件中的线程安全,您可以在此处阅读:
C#事件和线程安全
鉴于此代码:
static void Main(string[] args)
{
var a = new Random(1).Next() > 0 ? new object() : null;
var b = a?.GetHashCode();
Console.WriteLine(b);
}
Run Code Online (Sandbox Code Playgroud)
这就是我在IL表示中看到的行,其中monadic运算符在Release模式下被调用(VS 2015):
IL_0016: dup
IL_0017: brtrue.s IL_0025
... //nothing iteresting, just setting null to 'a' and skip IL_0025 area
IL_0025: callvirt instance int32 [mscorlib]System.Object::GetHashCode()
Run Code Online (Sandbox Code Playgroud)
让我解释:
所以,回答你的问题是:是的,使用monadic运算符是线程安全的,因为它是在副本上运行的.