开发者

Dispoable pattern with c#4.0 & vs2010 [duplicate]

开发者 https://www.devze.com 2023-02-25 15:21 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: C# Finalize/Dispose pattern
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

C# Finalize/Dispose pattern

How should I go about implementing disposable pattern (IDisposable interface) properly with vs2010 and c#4? A quick example and and important tip would be so nice.

I know there are c#2 examples but asking more for c#4.

Edit: Alright please delete开发者_运维知识库 the question (as I cant). I now see that nothing with respect to object disposal have changed since c#2.0 to 4.0


The same way as in previous versions of C#. The recommended pattern goes along those lines:

class MyClass : IDisposable
{

    ~MyClass()
    {
        Dispose(false);
    }

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

    private bool disposed = false;
    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // Dispose managed resources
            }
            // Dispose unmanaged resources

            disposed = true;
        }
    }

}

See this MSDN page for details.


The basic pattern.

    /// <summary>
    /// Dispose Method
    /// </summary>
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    /// <summary>
    /// Deconstructor
    /// </summary>
    ~[PutYourClassHere]()
    {
        Dispose(false);
    }
    /// <summary>
    /// IDisposable Implementation
    /// </summary>
    /// <param name="disposing">Disposing Flag</param>
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            //Free Managed Resources
        }

        //Free Native Resources 
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号