如何为类编写析构函数? [英] How to write a destructor for a class?

查看:159
本文介绍了如何为类编写析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类:

public class test
{
       public int datacapturecount { get; set; }
       public int sno { get; set; }
       public string name { get; set; }
       public string sourceaddr { get; set; }
       public string destaddr { get; set; }
       public string Bssid { get; set; }
       public string packetsubtype { get; set; }
       public UInt16 datarate { get; set; }
       public SByte signal { get; set; }
       public UInt32 channel { get; set; }
       public UInt32 size { get; set; }
}

我正在使用这个类,同时向wpf datagrid添加行在无限循环中对于(I = 0;; I ++)
{
datagrid.Items.Add(new),

I am using this class while adding rows to wpf datagrid In a infinite loop:

for(I=0; ; I++)
{
    datagrid.Items.Add(new test() {
        datacapturecount = 0, 
        sno = I,
        name = "ssss",
        sourceaddr = "44545454"
    }); 
}

这里的类测试正在创建多个实例并导致内存泄漏。如何避免这种情况?
如何为上面的类编写析构函数,以便在将行添加到datagrid后,可以立即强制GC收集内存?

Here the class test is creating multiple instances and causing memory leaks. How to avoid this? How to Write destructor for above class so that I can force the GC to collect the memory immediately after adding the row to datagrid?

推荐答案

没有内存泄漏。每个类实例都被添加到 datagrid.Items 中,所以你始终保持对 datagrid.Items 的引用,对 test 实例的引用必须保留在内存中。因为您在添加项目时有无限循环,代码将运行,直到内存不足。

There is no memory leak. Each class instance is being added to datagrid.Items, so all the time you keep a reference to datagrid.Items, the references to test instances have to remain in memory. Because you have an infinite loop around adding items, the code will run until it runs out of memory.

添加析构函数或 IDisposible 这个类将不会有任何影响。您需要管理您添加到 datagrid.Items 的项目数。

Adding a destructor or IDisposible to this class will have no affect. You need to manage the number of items you add to datagrid.Items.

这篇关于如何为类编写析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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