哪个是调用事件委托的更好方法?

kam*_*dra 7 c# events event-handling

private void NotifyFreeChannelsChanged() //1.
{
    if (FreeChannelsChanged != null)
    {
        FreeChannelsChanged(this, null);
    }
}

private void NotifyFreeChannelsChanged() //2.
{
    NotifyCollectionChangedEventHandler h = FreeChannelsChanged ;
     if (h != null)
         h(this, e);
}
Run Code Online (Sandbox Code Playgroud)

出于这些更好,为什么.或者它只是一个额外的检查.不是一个主要的区别.

Ed *_* S. 6

"更好"?好吧,不包含(特定的)竞争条件,一个.MultiCastDelegate类型是不可变的,并且在所有重要的方式中使用值类型语义(但它们引用类型,请参阅,更重要的是,这一点),这就是您首先分配它然后检查的原因.问题是:

// this evaluates to true...
if(SomeEvent != null)
{
    // ...but before this line executes, the last 
    // subscriber detached, and now SomeEvent is null. Oops.
    SomeEvent(this, e);
}
Run Code Online (Sandbox Code Playgroud)

您应该问"为什么有人会使用示例#2?"


顺便说一句,这是一个使用隐式类型变量(var)的好地方.那些委托类型名称变长了......

同样有趣的是,竞争条件仍然存在,它只是更微妙.如果订户在转让后被删除会怎样?好吧,它仍然会被调用,但实际上没有(我知道)你可以做到这一点.