相关疑难解决方法(0)

在应用程序关闭时将信息存储到文件的正确方法

我的一个类在应用程序执行期间收集统计信息,我希望在应用程序完成时将此统计信息存储到磁盘.我从来没有在我的程序中销毁这个类,所以我试图将日志存储到文件中:

    ~Strategy()
    {
        foreach(var item in statisticItems)
        {
            log.WriteLine(item.Text);    // log is AutoFlush
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是我没有看到我期望看到的日志,并且在析构函数调用时我也无法在调试器中"捕获".

问题:

  • 为什么在调试器中我无法捕获析构函数被调用的时刻?程序完成后,是否必须为每个对象调用析构函数?
  • 我应该用什么来记录我的东西?

c#

6
推荐指数
1
解决办法
110
查看次数

C#析构函数未按预期工作

请参阅下面的代码.我希望它打印10,因为我已经显式调用了垃圾收集器.但我总是输出0或20作为输出.这是为什么?

void Main()
{
    Panda[] forest_panda = new Panda[10];
    for(int i=0; i<forest_panda.GetLength(0);i++)
    {
        forest_panda[i]=new Panda("P1");
    }

    for(int i=0; i<forest_panda.GetLength(0);i++)
    {
        forest_panda[i]=new Panda("P1");
    }

    System.GC.Collect();

    Console.WriteLine("Total Pandas created is {0}",Panda.population);          
}

class Panda
{
    public static int population=0;
    public string name;

    public Panda(string name)
    {
        this.name = name;
        population = population + 1;
    }

    ~Panda()
    {
        population = population - 1;
    }   
}
Run Code Online (Sandbox Code Playgroud)

请注意,Main的类是由LINQPad("Nutshell中的C#4.0"一书中的编辑器)自动创建的.我是C#的新手.

c# garbage-collection destructor

5
推荐指数
2
解决办法
3811
查看次数

标签 统计

c# ×2

destructor ×1

garbage-collection ×1