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



我的对象有一个小问题...我有一个在其中订阅构造函数的对象。当我销毁此对象时,调用列表仍然告诉我它有一个订户。何时再创建此对象,我在其中找到了两个订户(我已经销毁的旧订户和新对象(。如何解决此问题并清除列表中的订户?

这是测试的代码:(两个按钮销毁并在内部创建对象(

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

感谢您的帮助。

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

这并没有真正破坏对象。物体被垃圾收集器"释放"(释放(。

实际上,它不能将其标记为可收集,因为static委托仍然引用它。因此,从来没有称呼攻击器。您已经手动删除了订户,例如通过公共方法。

,因为您无法手动调用destructor,为什么不实现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();
}

最新更新