0

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

Community
  • 1
  • 1
Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
  • 2
    Adobe what? You're missing some vital information here.... – Bob G Apr 15 '11 at 14:55
  • 2
    Duplicate. Nothing has change with Dispose in C# 4.0 so the answer qes suggests is still valid. – Ade Miller Apr 15 '11 at 15:04
  • Can you imagine what the consequences would be on legacy code if Microsoft changed the Dispose pattern for .NET 4? – MattDavey Apr 15 '11 at 15:58
  • 1
    @MattDavey: Changing recommended Dispose pattern for future code wouldn't have to break legacy code. There are some defects in Microsoft's pattern (e.g. it requires every level of a hierarchy to maintain its own "isDisposed" flag, and it wrongly encourages classes to be designed for the possibility of child classes adding a Finalize routine for cleanup); the only problem I could see would be that a programmer who inherits from an old class might expect it to provide a DisposeBegun flag when it doesn't, but that should be easy enough to deal with when it happens. – supercat Apr 16 '11 at 19:02

2 Answers2

2

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.

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
0

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 
    }
Jon Raynor
  • 84
  • 1
  • 1