Setting an Event to Null

I have a code like this:

public class SomeClass
{
    int _processProgress;
    public int ProcessProgress 
    { 
        get { return _processProgress; } 
        set 
        { 
            _processProgress = value; 
            if (ProcessProgressChanged != null) 
                ProcessProgressChanged(value);
        } 
    }

    public delegate void ProcessProgressChangedEventHandler(int progressPercentage);
    public event ProcessProgressChangedEventHandler ProcessProgressChanged;

    public void ClearProcessProgressChangedEvent()
    {
        this.ProcessProgressChanged = null;
    }
}

Will it unsubscribe all method in the ProcessProgressChanged event when I call the ClearProcessProgressChangedEvent() method?

My code is in C#, framework 4, build in VS2010 Pro, project is in Winforms.

 

Well, it'll effectively clear the list of subscribers, yes (by setting the underlying delegate field to null) - so that the next time ProcessProgress is set, no handlers will be called. It's not really setting theevent to null - it's setting the underlying field to null. It's just that the C# compiler is creating both an event (a subscribe/unsubscribe pair of methods) and a field (to store the handlers) using a single declaration.

You may find my article about events and delegates useful.

Note that your event-raising code currently isn't thread-safe. I don't know whether it needs to be or not, but you might want to consider using:

set 
{ 
    _processProgress = value; 
    var handlers = ProcessProgressChanged;
    if (handlers != null) 
    {
        handlers(value);
    }
}

That way you won't get a NullReferenceException if the last handler is unsubscribed after the nullity check but before the invocation.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值