zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    Python爬虫(七)
    Python爬虫(六)
    Python爬虫(五)
    爬取图片(二)
    爬取图片(一)
    爬虫的步骤
    selenium基础框架的封装(Python版)这篇帖子在百度关键词搜索的第一位了,有图为证,开心!
    自动化测试平台的探索
    文件上传自动化测试方案
    插入排序的性能测试对比(C与C++实现)
  • 原文地址:https://www.cnblogs.com/zjoch/p/4757026.html
Copyright © 2011-2022 走看看