IDisposable.Dispose Yöntem
Tanım
Önemli
Bazı bilgiler ürünün ön sürümüyle ilgilidir ve sürüm öncesinde önemli değişiklikler yapılmış olabilir. Burada verilen bilgilerle ilgili olarak Microsoft açık veya zımni hiçbir garanti vermez.
Yönetilmeyen kaynakları serbest bırakma, serbest bırakma veya sıfırlama ile ilişkili uygulama tanımlı görevleri gerçekleştirir.
public:
void Dispose();
public void Dispose();
abstract member Dispose : unit -> unit
Public Sub Dispose ()
Örnekler
Aşağıdaki örnekte yöntemini nasıl uygulayabileceğiniz gösterilmektedir 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
Açıklamalar
Bu arabirimi uygulayan sınıfın bir örneği tarafından tutulan dosyalar, akışlar ve tanıtıcılar gibi yönetilmeyen kaynakları kapatmak veya serbest bırakmak için bu yöntemi kullanın. Kurala göre, bu yöntem bir nesne tarafından tutulan kaynakları boşaltma veya nesneyi yeniden kullanmak üzere hazırlama ile ilişkili tüm görevler için kullanılır.
Warning
Arabirimini uygulayan IDisposable bir sınıf kullanıyorsanız, sınıfını kullanmayı bitirdiğinizde onun Dispose uygulamasını çağırmanız gerekir. Daha fazla bilgi için konunun "IDisposable uygulayan bir nesne kullanma" bölümüne IDisposable bakın.
Bu yöntemi uygularken, çağrıyı kapsama hiyerarşisi aracılığıyla dağıtarak tutulan tüm kaynakların serbest olduğundan emin olun. Örneğin, A nesnesi bir B nesnesi ayırırsa ve B nesnesi bir C nesnesi ayırırsa, A'nın Dispose uygulaması B'de çağrı Dispose yapmalıdır ve bu da C'de çağrı Dispose yapmalıdır.
Important
C++ derleyicisi kaynakların belirlenimici bir şekilde elden geçirilmesini destekler ve yöntemin doğrudan uygulanmasına Dispose izin vermez.
Temel sınıf uygularsaDispose, bir nesnenin de temel sınıfının yöntemini çağırması IDisposable gerekir. Temel sınıfa ve alt sınıflarına uygulama IDisposable hakkında daha fazla bilgi için konunun "IDisposable ve devralma hiyerarşisi" bölümüne IDisposable bakın.
Bir nesnenin Dispose yöntemi birden fazla kez çağrılırsa, nesne ilk çağrıdan sonrakileri görmezden gelmelidir. Yöntemi birden çok kez çağrılırsa Dispose nesne özel durum oluşturmamalıdır. dışındaki Dispose örnek yöntemleri, kaynaklar zaten atıldığında bir ObjectDisposedException oluşturabilir.
Kullanıcılar bir kaynak türünün ayrılmış durumu ve serbest durumdaki durumu belirtmek için belirli bir kuralı kullanmasını bekleyebilir. Buna örnek olarak, geleneksel olarak açık veya kapalı olarak düşünülen akış sınıfları örnek olarak verilmiştir. Böyle bir kurala sahip bir sınıfın uygulayıcısı, yöntemini Closeçağıran Dispose gibi özelleştirilmiş bir ada sahip genel bir yöntem uygulamayı seçebilir.
Yöntemin Dispose açıkça çağrılması gerektiğinden, bir nesnenin tüketicisi yöntemini çağıramadığından yönetilmeyen kaynakların serbest bırakılmaması her zaman bir tehlike oluşturur Dispose . Bunu önlemenin iki yolu vardır:
Yönetilen kaynağı öğesinden System.Runtime.InteropServices.SafeHandletüretilen bir nesneye sarmalama. Uygulamanız Dispose daha sonra örneklerin DisposeSystem.Runtime.InteropServices.SafeHandle yöntemini çağırır. Daha fazla bilgi için konunun "SafeHandle alternatifi Object.Finalize " bölümüne bakın.
Çağrılmadığında Dispose kaynakları boşaltmak için sonlandırıcı uygulayın. Varsayılan olarak, çöp toplayıcı, belleğini geri kazanmadan önce nesnenin sonlandırıcısını otomatik olarak çağırır. Ancak yöntemi çağrıldıysa Dispose , çöp toplayıcının atılan nesnenin sonlandırıcısını çağırması genellikle gereksizdir. Otomatik sonlandırmayı Dispose önlemek için uygulamalar yöntemini çağırabilir GC.SuppressFinalize .
gibi yönetilmeyen kaynaklara erişen bir StreamWriternesne kullandığınızda, örneği bir deyimiyle oluşturmak iyi bir using uygulamadır. deyimi using akışı otomatik olarak kapatır ve bunu kullanan kod tamamlandığında nesnesine çağrılar Dispose . Bir örnek için sınıfına StreamWriter bakın.