相关疑难解决方法(0)

了解.NET中的垃圾收集

考虑以下代码:

public class Class1
{
    public static int c;
    ~Class1()
    {
        c++;
    }
}

public class Class2
{
    public static void Main()
    {
        {
            var c1=new Class1();
            //c1=null; // If this line is not commented out, at the Console.WriteLine call, it prints 1.
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.WriteLine(Class1.c); // prints 0
        Console.Read();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,即使main方法中的变量c1超出范围并且在GC.Collect()调用时没有被任何其他对象进一步引用,为什么它没有在那里完成?

.net c# garbage-collection

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

使用Object Initializer的复活差异

我有这个代码:

基本上我正在尝试演示使用c#终结器并制作一个不能死的对象,我称之为Zombie.现在,通常这个演示工作得很好,但今天我尝试使用与对象初始化器相同的代码而不是仅仅分配给属性(在这种情况下为Name).我注意到有区别.即使终结器永远不会被调用,即使我正在尽最大努力使垃圾收集器完成它的工作.

有人可以解释这个区别,还是我在C#编译器中发现了一个错误?

(我在Win7x64上使用VS2010 SP1中的C#4)

谢谢.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Zombie
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Main thread: " + Thread.CurrentThread.ManagedThreadId);

              // case 1: this is where the problem is located.
      Zombie z = new Zombie { Name = "Guy" }; // object initializer syntax makes that the finalizer is not called.

              // case 2: this is not causing a problem. The finalizer gets called.
      //Zombie z = new …
Run Code Online (Sandbox Code Playgroud)

c# garbage-collection finalizer

5
推荐指数
1
解决办法
1609
查看次数

标签 统计

c# ×2

garbage-collection ×2

.net ×1

finalizer ×1