IDisposable.Dispose Metoda

Definice

Provádí úlohy definované aplikací související s uvolněním, uvolněním nebo resetováním nespravovaných prostředků.

public:
 void Dispose();
public void Dispose();
abstract member Dispose : unit -> unit
Public Sub Dispose ()

Příklady

Následující příklad ukazuje, jak můžete implementovat metodu Dispose .

using System;
using System.ComponentModel;

// The following example demonstrates how to create
// a resource class that implements the IDisposable interface
// and the IDisposable.Dispose method.

public class DisposeExample
{
    // A base class that implements IDisposable.
    // By implementing IDisposable, you are announcing that
    // instances of this type allocate scarce resources.
    public class MyResource: IDisposable
    {
        // Pointer to an external unmanaged resource.
        private IntPtr handle;
        // Other managed resource this class uses.
        private Component component = new Component();
        // Track whether Dispose has been called.
        private bool disposed = false;

        // The class constructor.
        public MyResource(IntPtr handle)
        {
            this.handle = handle;
        }

        // Implement IDisposable.
        // Do not make this method virtual.
        // A derived class should not be able to override this method.
        public void Dispose()
        {
            Dispose(disposing: true);
            // This object will be cleaned up by the Dispose method.
            // Therefore, you should call GC.SuppressFinalize to
            // take this object off the finalization queue
            // and prevent finalization code for this object
            // from executing a second time.
            GC.SuppressFinalize(this);
        }

        // Dispose(bool disposing) executes in two distinct scenarios.
        // If disposing equals true, the method has been called directly
        // or indirectly by a user's code. Managed and unmanaged resources
        // can be disposed.
        // If disposing equals false, the method has been called by the
        // runtime from inside the finalizer and you should not reference
        // other objects. Only unmanaged resources can be disposed.
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if(!this.disposed)
            {
                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if(disposing)
                {
                    // Dispose managed resources.
                    component.Dispose();
                }

                // Call the appropriate methods to clean up
                // unmanaged resources here.
                // If disposing is false,
                // only the following code is executed.
                CloseHandle(handle);
                handle = IntPtr.Zero;

                // Note disposing has been done.
                disposed = true;
            }
        }

        // Use interop to call the method necessary
        // to clean up the unmanaged resource.
        [System.Runtime.InteropServices.DllImport("Kernel32")]
        private extern static Boolean CloseHandle(IntPtr handle);

        // Use C# finalizer syntax for finalization code.
        // This finalizer will run only if the Dispose method
        // does not get called.
        // It gives your base class the opportunity to finalize.
        // Do not provide finalizer in types derived from this class.
        ~MyResource()
        {
            // Do not re-create Dispose clean-up code here.
            // Calling Dispose(disposing: false) is optimal in terms of
            // readability and maintainability.
            Dispose(disposing: false);
        }
    }
    public static void Main()
    {
        // Insert code here to create
        // and use the MyResource object.
    }
}
// The following example demonstrates how to create
// a resource class that implements the IDisposable interface
// and the IDisposable.Dispose method.
open System
open System.ComponentModel
open System.Runtime.InteropServices

// Use interop to call the method necessary
// to clean up the unmanaged resource.
[<DllImport "Kernel32">]
extern Boolean CloseHandle(nativeint handle)

// A base class that implements IDisposable.
// By implementing IDisposable, you are announcing that
// instances of this type allocate scarce resources.
type MyResource(handle: nativeint) =
    // Pointer to an external unmanaged resource.
    let mutable handle = handle

    // Other managed resource this class uses.
    let comp = new Component()
    
    // Track whether Dispose has been called.
    let mutable disposed = false

    // Implement IDisposable.
    // Do not make this method virtual.
    // A derived class should not be able to override this method.
    interface IDisposable with
        member this.Dispose() =
            this.Dispose true
            // This object will be cleaned up by the Dispose method.
            // Therefore, you should call GC.SuppressFinalize to
            // take this object off the finalization queue
            // and prevent finalization code for this object
            // from executing a second time.
            GC.SuppressFinalize this

    // Dispose(bool disposing) executes in two distinct scenarios.
    // If disposing equals true, the method has been called directly
    // or indirectly by a user's code. Managed and unmanaged resources
    // can be disposed.
    // If disposing equals false, the method has been called by the
    // runtime from inside the finalizer and you should not reference
    // other objects. Only unmanaged resources can be disposed.
    abstract Dispose: bool -> unit
    override _.Dispose(disposing) =
        // Check to see if Dispose has already been called.
        if not disposed then
            // If disposing equals true, dispose all managed
            // and unmanaged resources.
            if disposing then
                // Dispose managed resources.
                comp.Dispose()

            // Call the appropriate methods to clean up
            // unmanaged resources here.
            // If disposing is false,
            // only the following code is executed.
            CloseHandle handle |> ignore
            handle <- IntPtr.Zero

            // Note disposing has been done.
            disposed <- true


    // This finalizer will run only if the Dispose method
    // does not get called.
    // It gives your base class the opportunity to finalize.
    // Do not provide finalizer in types derived from this class.
    override this.Finalize() =
        // Do not re-create Dispose clean-up code here.
        // Calling Dispose(disposing: false) is optimal in terms of
        // readability and maintainability.
        this.Dispose false
Imports System.ComponentModel

' The following example demonstrates how to create
' a resource class that implements the IDisposable interface
' and the IDisposable.Dispose method.
Public Class DisposeExample

   ' A class that implements IDisposable.
   ' By implementing IDisposable, you are announcing that
   ' instances of this type allocate scarce resources.
   Public Class MyResource
      Implements IDisposable
      ' Pointer to an external unmanaged resource.
      Private handle As IntPtr
      ' Other managed resource this class uses.
      Private component As component
      ' Track whether Dispose has been called.
      Private disposed As Boolean = False

      ' The class constructor.
      Public Sub New(ByVal handle As IntPtr)
         Me.handle = handle
      End Sub

      ' Implement IDisposable.
      ' Do not make this method virtual.
      ' A derived class should not be able to override this method.
      Public Overloads Sub Dispose() Implements IDisposable.Dispose
         Dispose(disposing:=True)
         ' This object will be cleaned up by the Dispose method.
         ' Therefore, you should call GC.SupressFinalize to
         ' take this object off the finalization queue
         ' and prevent finalization code for this object
         ' from executing a second time.
         GC.SuppressFinalize(Me)
      End Sub

      ' Dispose(bool disposing) executes in two distinct scenarios.
      ' If disposing equals true, the method has been called directly
      ' or indirectly by a user's code. Managed and unmanaged resources
      ' can be disposed.
      ' If disposing equals false, the method has been called by the
      ' runtime from inside the finalizer and you should not reference
      ' other objects. Only unmanaged resources can be disposed.
      Protected Overridable Overloads Sub Dispose(ByVal disposing As Boolean)
         ' Check to see if Dispose has already been called.
         If Not Me.disposed Then
            ' If disposing equals true, dispose all managed
            ' and unmanaged resources.
            If disposing Then
               ' Dispose managed resources.
               component.Dispose()
            End If

            ' Call the appropriate methods to clean up
            ' unmanaged resources here.
            ' If disposing is false,
            ' only the following code is executed.
            CloseHandle(handle)
            handle = IntPtr.Zero

            ' Note disposing has been done.
            disposed = True

         End If
      End Sub

      ' Use interop to call the method necessary
      ' to clean up the unmanaged resource.
      <System.Runtime.InteropServices.DllImport("Kernel32")> _
      Private Shared Function CloseHandle(ByVal handle As IntPtr) As [Boolean]
      End Function

      ' This finalizer will run only if the Dispose method
      ' does not get called.
      ' It gives your base class the opportunity to finalize.
      ' Do not provide finalize methods in types derived from this class.
      Protected Overrides Sub Finalize()
         ' Do not re-create Dispose clean-up code here.
         ' Calling Dispose(disposing:=False) is optimal in terms of
         ' readability and maintainability.
         Dispose(disposing:=False)
         MyBase.Finalize()
      End Sub
   End Class

   Public Shared Sub Main()
      ' Insert code here to create
      ' and use the MyResource object.
   End Sub

End Class

Poznámky

Tuto metodu použijte k zavření nebo uvolnění nespravovaných prostředků, jako jsou soubory, datové proudy a obslužné rutiny uchovávané instancí třídy, která implementuje toto rozhraní. Podle konvence se tato metoda používá pro všechny úlohy spojené s uvolněním prostředků uchovávaných objektem nebo přípravou objektu pro opakované použití.

Warning

Pokud používáte třídu, která implementuje IDisposable rozhraní, měli byste po dokončení používání třídy volat její Dispose implementaci. Další informace naleznete v části Použití objektu, který implementuje IDisposable v IDisposable tématu.

Při implementaci této metody zajistěte, aby všechny uchovávané prostředky byly uvolněny šířením volání prostřednictvím hierarchie omezení. Pokud například objekt A přiděluje objekt B a objekt B přidělí objekt C, pak implementace A Dispose musí volat Dispose B, což musí zase volat Dispose C.

Important

Kompilátor C++ podporuje deterministické odstranění prostředků a neumožňuje přímou Dispose implementaci metody.

Objekt musí také volat metodu Dispose své základní třídy, pokud základní třída implementuje IDisposable. Další informace o implementaci IDisposable základní třídy a jejích podtříd najdete v části IDisposable a hierarchie dědičnosti v IDisposable tématu.

Pokud je metoda Dispose objektu volána více než jednou, musí objekt ignorovat všechna volání po prvním. Objekt nesmí vyvolat výjimku, pokud je jeho Dispose metoda volána vícekrát. Jiné metody instance, než Dispose mohou vyvolat, ObjectDisposedException když jsou prostředky již uvolněny.

Uživatelé můžou očekávat, že typ prostředku použije konkrétní konvenci k označení přiděleného stavu a uvolněného stavu. Příkladem je třídy datových proudů, které se tradičně považují za otevřené nebo uzavřené. Implementátor třídy, která má takovou konvenci, se může rozhodnout implementovat veřejnou metodu s přizpůsobeným názvem, například Close, který volá metodu Dispose .

Dispose Vzhledem k tomu, že metoda musí být volána explicitně, existuje vždy nebezpečí, že nespravované prostředky nebudou uvolněny, protože příjemce objektu nemůže volat jeho Dispose metodu. Existují dva způsoby, jak se tomu vyhnout:

  • Zabalte spravovaný prostředek do objektu odvozeného z System.Runtime.InteropServices.SafeHandle. Vaše Dispose implementace pak volá Dispose metodu System.Runtime.InteropServices.SafeHandle instancí. Další informace najdete v části Alternativní dokumentace SafeHandle v Object.Finalize tématu.

  • Implementujte finalizační metodu pro bezplatné prostředky, pokud Dispose není volána. Ve výchozím nastavení systém uvolňování paměti před uvolněním paměti automaticky volá finalizátor objektu. Nicméně, pokud Dispose byla volána metoda, je obvykle zbytečné, aby uvolňování paměti volání finalizátoru odstraněného objektu. Aby se zabránilo automatické finalizaci, Dispose implementace mohou volat metodu GC.SuppressFinalize .

Pokud používáte objekt, který přistupuje k nespravovaným prostředkům, jako StreamWriterje například , dobrým postupem je vytvořit instanci pomocí using příkazu. Příkaz using automaticky zavře datový proud a volá Dispose objekt po dokončení kódu, který ho používá. Podívejte se například na StreamWriter třídu.

Platí pro

Viz také