销毁对象不会从调用列表中删除委托

时间:2017-06-08 07:41:19

标签: c# object delegates destroy

我的对象有点问题...... 我有一个对象,里面有一个委托,它在构造函数中订阅。 当我销毁这个对象时,调用列表仍然告诉我它有一个订阅者。当再次创建这个对象时,我发现两个订阅者(我已经销毁的旧订阅者和新订阅者)。 如何解决此问题并彻底删除列表中的订户?

以下是测试代码:(两个按钮用于销毁和创建对象)

public partial class Form1 : Form
{
    testdelegate thisdelegatetest;
    public Form1()
    {
        InitializeComponent();
        thisdelegatetest = new testdelegate();//create object 
        Timer mytimer = new Timer();//timer to see something BEGIN
        mytimer.Interval = 1000;
        mytimer.Tick += new EventHandler(mytimer_Tick);
        mytimer.Start();//timer to see something END
    }
    protected void mytimer_Tick(object sender, EventArgs e)
    {//each 1second look at the list invocation
        lb_IndelList.Text = "actual subscribers : " + testdelegate.dl_myfunctionthatcopy.GetInvocationList().Count().ToString();
    }
    private void DestroyObject_Click(object sender, EventArgs e)
    {//destroy object
    /*edit*/
        thisdelegatetest.Delete();
        thisdelegatetest = null;//dereferencing for GC
    /*edit*/
    }

    private void CreateObject_Click(object sender, EventArgs e)
    {//create object
        thisdelegatetest = new testdelegate();
    }

}
public class testdelegate
{
    public delegate void del_copysomething(int newvaluetocopy);
    internal static del_copysomething dl_myfunctionthatcopy;
    public int valueforallobject = 0;

    public testdelegate()//ctor
    {
        dl_myfunctionthatcopy += new del_copysomething(copythisint);
    }
    /*edit*/
    public void Delete()
    { 
        dl_myfunctionthatcopy -= new del_copysomething(copythisint);
    }
    /*edit*/
    private void copythisint(int newvalue)
    {
        valueforallobject = newvalue;
    }
}

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

private void DestroyObject_Click(object sender, EventArgs e)
{//destroy object
    thisdelegatetest = null;
}

这并没有真正破坏对象。对象被垃圾收集器“销毁”(释放)。

事实上,不能被标记为可收集,因为static委托仍然引用它。因此,从不调用析构函数。您已手动删除订户,例如通过公共方法。

答案 1 :(得分:0)

由于无法手动调用析构函数,为什么不实现IDisposable接口并在Dispose方法中执行取消注册?=!

public class testdelegate : IDisposable
{
    public delegate void del_copysomething(int newvaluetocopy);
    internal static del_copysomething dl_myfunctionthatcopy;
    public int valueforallobject = 0;

    public testdelegate()//ctor
    {
        dl_myfunctionthatcopy += new del_copysomething(copythisint);
    }
    private void copythisint(int newvalue)
    {
        valueforallobject = newvalue;
        Console.WriteLine("Copied");
    }

    public void Dispose()
    {
        dl_myfunctionthatcopy -= new del_copysomething(copythisint);
        GC.SuppressFinalize(this);
    }
}

DestroyObject_Click方法中,您只需调用Dispose方法:

private void DestroyObject_Click(object sender, EventArgs e)
{   //call Dispose destroy object
    thisdelegatetest.Dispose();
}