在下列情况下如何确保没有内存泄漏

use*_*949 4 .net c#

如果类具有包含非托管资源的属性.使用该类时如何确保没有内存泄漏

Class A
{
         B {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

B包含非托管资源.

Phi*_*unt 7

IDisposable通过调用来实现和清理非托管资源Dispose(),最好将调用Dispose放在finally语句中,这样即使在异常的情况下也可以清理资源.

C#有一个using关键字,您可以使用该关键字来确保Dispose调用该方法,即使抛出异常也是如此.

编辑:根据Ran的答案合并调用GC.SuppressFinalize和终结器实现

class A : IDisposable
{
    private bool _disposed;

    ~A()
    {
        this.Dispose(false);
    }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                // dispose managed resources
            }

            // clean up unmanaged resources

            _disposed = true;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        using (var someInstance = new A())
        {
            // do some things with the class.
            // once the using block completes, Dispose
            // someInstance.Dispose() will automatically
            // be called
        }
    }
}
Run Code Online (Sandbox Code Playgroud)