IDisposable.Dispose Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Выполняет определяемые приложением задачи, связанные с освобождением, освобождением или сбросом неуправляемых ресурсов.
public:
void Dispose();
public void Dispose();
abstract member Dispose : unit -> unit
Public Sub Dispose ()
Примеры
В следующем примере показано, как реализовать 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
Комментарии
Используйте этот метод, чтобы закрыть или освободить неуправляемые ресурсы, такие как файлы, потоки и дескриптор, удерживаемые экземпляром класса, реализующего этот интерфейс. По соглашению этот метод используется для всех задач, связанных с освобождением ресурсов, удерживаемых объектом, или подготовкой объекта для повторного использования.
Предупреждение
Если вы используете класс, реализующий IDisposable интерфейс, следует вызвать его Dispose реализацию после завершения работы с классом. Дополнительные сведения см. в разделе "Использование объекта, реализующего IDisposable" в IDisposable разделе.
При реализации этого метода убедитесь, что все удерживаемые ресурсы освобождаются путем распространения вызова через иерархию хранения. Например, если объект A выделяет объект B, а объект B выделяет объект C, реализация A Dispose должна вызвать Dispose B, который должен включить вызов Dispose C.
Important
Компилятор C++ поддерживает детерминированное удаление ресурсов и не разрешает прямую Dispose реализацию метода.
Объект также должен вызвать Dispose метод своего базового класса, если базовый класс реализует IDisposable. Дополнительные сведения о реализации IDisposable базового класса и его подклассах см. в разделе "IDisposable и иерархия наследования" раздела IDisposable .
Если метод Dispose объекта вызывается несколько раз, объект должен игнорировать все вызовы после первого. Объект не должен вызывать исключение, если его метод Dispose вызывается несколько раз. Методы экземпляров, отличные от Dispose методов, которые могут вызывать ObjectDisposedException , когда ресурсы уже удалены.
Пользователи могут ожидать, что тип ресурса будет использовать определенное соглашение для обозначения выделенного состояния и свободного состояния. Примером этого является потоковые классы, которые традиционно считаются открытыми или закрытыми. Реализующий класс, имеющий такое соглашение, может выбрать реализацию общедоступного метода с настраиваемым именем, например Close, который вызывает Dispose метод.
Dispose Так как метод должен вызываться явным образом, всегда существует опасность того, что неуправляемые ресурсы не будут освобождены, так как потребитель объекта не вызывает его Dispose метод. Избежать этого можно двумя способами:
Перенос управляемого ресурса в объект, производный от System.Runtime.InteropServices.SafeHandle. Затем реализация Dispose вызывает Dispose метод System.Runtime.InteropServices.SafeHandle экземпляров. Дополнительные сведения см. в Object.Finalize разделе "Альтернатива SafeHandle".
Реализуйте метод завершения для бесплатных ресурсов, когда Dispose не вызывается. По умолчанию сборщик мусора автоматически вызывает метод завершения объекта перед освобождением памяти. Однако если Dispose метод был вызван, то обычно не требуется сборщику мусора вызывать метод завершения удаленного объекта. Чтобы предотвратить автоматическую Dispose завершение, GC.SuppressFinalize реализации могут вызывать метод.
При использовании объекта, который обращается к неуправляемым ресурсам, например StreamWriter, рекомендуется создать экземпляр с помощью инструкции using . Оператор using автоматически закрывает поток и вызывает Dispose объект при завершении кода, используемого им. Пример см StreamWriter . в классе.