C#单例模式下内存不会释放

Memory will not release in C# singleton mode

我对单例模式在 C# 和 C++ 之间释放对象内存有一个困惑; 这里的 C++ 代码:

#include<iostream>
using namespace std;
class Rocket
{
private:
    Rocket() { speed = 100; }
    ~Rocket() {}
    static Rocket* ms_rocket;
public:
    int speed;
    static Rocket*ShareRocket()
    {
        if (ms_rocket == NULL)
            ms_rocket = new Rocket();
        return ms_rocket;
    }
    static void Close()
    {
        if (ms_rocket != NULL)
            delete ms_rocket;
    }
};
Rocket *Rocket::ms_rocket = NULL;
int main()
{
    Rocket* p =  Rocket::ShareRocket();
    p->speed = 100;
    cout << p->speed << endl;
    Rocket::Close();
    cout << p->speed << endl;
    getchar();
}

当我使用Rocket::Close()时,ms_rocket指向的内存space会被释放,ms_rocket变成野指针,第二个"cout

    class A : IDisposable
    {
        public int age;
        public A() {  }
        public void Run()
        {
            Console.WriteLine("Run");
        }
        #region IDisposable Support
        private bool disposedValue = false; 

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    Console.WriteLine("A is release");
                }
                disposedValue = true;

            }
        }
        public void Dispose()
        {
            Dispose(true);
        }
        #endregion
    }

    class B
    {
        static A a;
        private B() { }
        public static A Intance
        {
            get
            {
                if (a == null)
                    a = new A();
                return a;
            }
        }

    }
    class Class1
    {

        public static void Main(string[] args)
        {
            A a = B.Intance;
            a.age =100;
            Console.WriteLine(a.age);
            a.Dispose();
            A a1 = B.Intance;
            Console.WriteLine(a1.age);
            Console.Read();
        }
    }

在C#中,我想当我使用Dispose()时,内存('a' B单例中的对象)会被释放,但是在第二次访问时,age值应该不是100,并且静态变量 'a' 将变得像一个野指针。 谁能告诉我为什么?

在 C# 中 Dispose mainly is used to release unmanaged resources 一旦不需要它们并且不释放对象本身占用的内存 - 它由垃圾收集器处理,它将释放(当 GC 决定它需要 运行) 仅当它无法从所谓的 GC 根访问时(静态变量是 GC 根之一,因此 B.Intance 将在堆中保存对 A 实例的引用) .

因此,首先要释放 A 当前实例占用的内存,您需要将 B.Instance 设置为 null(并等待 GC 到 运行)。

CLR 中的 fundamentals of garbage collection 也很有用。