c#检查事件是否为空

时间:2013-02-08 13:28:43

标签: c# events null

我在网络服务中有这个事件:

public event FindProductsByCharacteristicsCompletedEventHandler FindProductsByCharacteristicsCompleted
    {
        [MethodImpl(MethodImplOptions.Synchronized)]
        add
        {
            _findProductsByCharacteristicsCompleted += value;
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        remove
        {
            _findProductsByCharacteristicsCompleted -= value;
        }
    }

然后我会在类中稍后检查事件值是否为null:

private void OnFindProductsByCharacteristicsOperationCompleted(object arg)
    {
        var handler = _findProductsByCharacteristicsCompleted;
        if (handler == null)
            return;
        handler(this, new FindProductsByCharacteristicsCompletedEventArgs(completedEventArgs.Results, completedEventArgs.Error, completedEventArgs.Cancelled, completedEventArgs.UserState));
    }

1 个答案:

答案 0 :(得分:2)

您的事件实现看起来像是无休止的递归。您在实施中使用了该属性 将其更改为:

private FindProductsByCharacteristicsCompletedEventHandler
            _findProductsByCharacteristicsCompleted;

public event FindProductsByCharacteristicsCompletedEventHandler
                 FindProductsByCharacteristicsCompleted 
{
    [MethodImpl(MethodImplOptions.Synchronized)]
    add
    {
        _findProductsByCharacteristicsCompleted += value;
    }
    [MethodImpl(MethodImplOptions.Synchronized)]
    remove
    {
        _findProductsByCharacteristicsCompleted -= value;
    }
}

现在,实现这样的方法:

var handler = _findProductsByCharacteristicsCompleted;
if(handler == null)
    return;

handler(this, new FindProductsByCharacteristicsCompletedEventArgs(...));

这样做的好处是它是线程安全的。

即使有人在您检查null之后但在实际引发事件之前从事件中分离了最后一个处理程序,您也不会得到异常,因为您正在对未更改的局部变量进行操作。