-2

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

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

然后我在类的后面用这个检查事件值是否为空:

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

1 回答 1

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 之后但在您实际引发事件之前从事件中分离了最后一个处理程序,您也不会收到异常,因为您正在对未更改的局部变量进行操作。

于 2013-02-08T13:30:24.127 回答