将事件设置为空 [英] Setting an Event to Null

查看:156
本文介绍了将事件设置为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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;
}
}

将它取消订阅 ClearProcessProgressChangedEvent()方法的 ProcessProgressChanged 事件中的所有方法



我的代码是C#,框架4,构建在VS2010 Pro中,项目在Winforms中。



请帮忙。感谢提前。

解决方案

嗯,它会有效地清除订阅者列表,是的(通过将底层代理字段设置为 null ) - 以便下次 ProcessProgress 设置时,不会调用任何处理程序。 事件并不真正设置为 null - 它将基础字段设置为 null 。只是C#编译器使用一个声明创建一个事件(一个订阅/取消订阅方法)和一个字段(存储处理程序)。



你可能会发现我的有关事件和代表的文章有用。



请注意,您的事件提升代码当前不是线程安全的。我不知道是否需要,但您可能希望使用以下方式

  set 
{
_processProgress = value;
var handlers = ProcessProgressChanged;
if(handlers!= null)
{
处理程序(值);
}
}

这样你就不会得到一个 NullReferenceException 如果最后一个处理程序在无效检查之后取消订阅,但

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.

Please help. Thanks in advance.

解决方案

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 the event 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.

这篇关于将事件设置为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆