IDisposable Interfejs
Definicja
Ważne
Niektóre informacje odnoszą się do produktu w wersji wstępnej, który może zostać znacząco zmodyfikowany przed wydaniem. Firma Microsoft nie udziela żadnych gwarancji, jawnych lub domniemanych, w odniesieniu do informacji podanych w tym miejscu.
Udostępnia mechanizm zwalniania niezarządzanych zasobów.
public interface class IDisposable
public interface IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public interface IDisposable
type IDisposable = interface
[<System.Runtime.InteropServices.ComVisible(true)>]
type IDisposable = interface
Public Interface IDisposable
- Pochodne
- Atrybuty
Przykłady
W poniższym przykładzie pokazano, jak utworzyć klasę zasobów, która implementuje IDisposable interfejs.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::ComponentModel;
using namespace System::Windows::Forms;
// The following example demonstrates how to create a class that
// implements the IDisposable interface and the IDisposable.Dispose
// method with finalization to clean up unmanaged resources.
//
public ref class MyResource: public IDisposable
{
private:
// Pointer to an external unmanaged resource.
IntPtr handle;
// A managed resource this class uses.
Component^ component;
// Track whether Dispose has been called.
bool disposed;
public:
// The class constructor.
MyResource( IntPtr handle, Component^ component )
{
this->handle = handle;
this->component = component;
disposed = false;
}
// This method is called if the user explicitly disposes of the
// object (by calling the Dispose method in other managed languages,
// or the destructor in C++). The compiler emits as a call to
// GC::SuppressFinalize( this ) for you, so there is no need to
// call it here.
~MyResource()
{
// Dispose of managed resources.
component->~Component();
// Call C++ finalizer to clean up unmanaged resources.
this->!MyResource();
// Mark the class as disposed. This flag allows you to throw an
// exception if a disposed object is accessed.
disposed = true;
}
// Use interop to call the method necessary to clean up the
// unmanaged resource.
//
[System::Runtime::InteropServices::DllImport("Kernel32")]
static Boolean CloseHandle( IntPtr handle );
// The C++ finalizer destructor ensures that unmanaged resources get
// released if the user releases the object without explicitly
// disposing of it.
//
!MyResource()
{
// Call the appropriate methods to clean up unmanaged
// resources here. If disposing is false when Dispose(bool,
// disposing) is called, only the following code is executed.
CloseHandle( handle );
handle = IntPtr::Zero;
}
};
void main()
{
// Insert code here to create and use the MyResource object.
MyResource^ mr = gcnew MyResource((IntPtr) 42, (Component^) gcnew Button());
mr->~MyResource();
}
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
Uwagi
Podstawowym zastosowaniem tego interfejsu jest zwolnienie niezarządzanych zasobów. Moduł odśmiecany automatycznie zwalnia pamięć przydzieloną do obiektu zarządzanego, gdy ten obiekt nie jest już używany. Nie można jednak przewidzieć, kiedy nastąpi odzyskiwanie pamięci. Ponadto moduł odśmiecanie pamięci nie ma wiedzy o niezarządzanych zasobach, takich jak uchwyty okien, ani otwieranie plików i strumieni.
Dispose Użyj metody tego interfejsu, aby jawnie zwolnić niezarządzane zasoby w połączeniu z modułem odśmiecającym pamięci. Odbiorca obiektu może wywołać tę metodę, gdy obiekt nie jest już potrzebny.
Ostrzeżenie
Jest to zmiana powodująca niezgodność w celu dodania interfejsu IDisposable do istniejącej klasy. Ponieważ wstępnie istniejący użytkownicy typu nie mogą wywołać Disposemetody , nie można mieć pewności, że zasoby niezarządzane przechowywane przez typ zostaną zwolnione.
Ponieważ implementacja IDisposable.Dispose jest wywoływana przez użytkownika typu, gdy zasoby należące do wystąpienia nie są już potrzebne, należy opakować obiekt zarządzany w (zalecaną SafeHandle alternatywę) lub przesłonić Object.Finalize do bezpłatnych niezarządzanych zasobów w przypadku, gdy użytkownik zapomni wywołać metodę Dispose.
Ważne
W .NET Framework kompilator języka C++ obsługuje deterministyczną usuwanie zasobów i nie zezwala na bezpośrednią implementację Dispose metody.
Szczegółowe omówienie sposobu użycia tego interfejsu Object.Finalize i metody można znaleźć w temacie Odzyskiwanie pamięci i Implementowanie metody dispose .
Używanie obiektu implementujące interfejs IDisposable
Jeśli aplikacja po prostu używa obiektu, który implementuje IDisposable interfejs, należy wywołać implementację obiektu IDisposable.Dispose po zakończeniu korzystania z niego. W zależności od języka programowania można to zrobić na jeden z dwóch sposobów:
Używając konstrukcji językowej, takiej jak
using
instrukcja w języku C# i Visual Basic, orazuse
instrukcja lubusing
funkcja w języku F#.Zawijając wywołanie implementacji IDisposable.Dispose w
try
/finally
bloku.
Uwaga
Dokumentacja typów, które implementują IDisposable fakt i zawierają przypomnienie, aby wywołać jego Dispose implementację.
Instrukcje C#, F# i Visual Basic Using
Jeśli język obsługuje konstrukcję, taką jak instrukcja using w języku C#, instrukcja Using w Visual Basic lub instrukcja use w języku F#, możesz użyć jej zamiast jawnie wywoływać IDisposable.Dispose siebie. W poniższym przykładzie użyto tego podejścia podczas definiowania WordCount
klasy, która zachowuje informacje o pliku i liczbie wyrazów w nim.
using System;
using System.IO;
using System.Text.RegularExpressions;
public class WordCount
{
private String filename = String.Empty;
private int nWords = 0;
private String pattern = @"\b\w+\b";
public WordCount(string filename)
{
if (!File.Exists(filename))
throw new FileNotFoundException("The file does not exist.");
this.filename = filename;
string txt = String.Empty;
using (StreamReader sr = new StreamReader(filename))
{
txt = sr.ReadToEnd();
}
nWords = Regex.Matches(txt, pattern).Count;
}
public string FullName
{ get { return filename; } }
public string Name
{ get { return Path.GetFileName(filename); } }
public int Count
{ get { return nWords; } }
}
open System.IO
open System.Text.RegularExpressions
type WordCount(filename) =
let txt =
if File.Exists filename |> not then
raise (FileNotFoundException "The file does not exist.")
use sr = new StreamReader(filename)
sr.ReadToEnd()
let pattern = @"\b\w+\b"
let nWords = Regex.Matches(txt, pattern).Count
member _.FullName = filename
member _.Name = Path.GetFileName filename
member _.Count = nWords
Imports System.IO
Imports System.Text.RegularExpressions
Public Class WordCount
Private filename As String
Private nWords As Integer
Private pattern As String = "\b\w+\b"
Public Sub New(filename As String)
If Not File.Exists(filename) Then
Throw New FileNotFoundException("The file does not exist.")
End If
Me.filename = filename
Dim txt As String = String.Empty
Using sr As New StreamReader(filename)
txt = sr.ReadToEnd()
End Using
nWords = Regex.Matches(txt, pattern).Count
End Sub
Public ReadOnly Property FullName As String
Get
Return filename
End Get
End Property
Public ReadOnly Property Name As String
Get
Return Path.GetFileName(filename)
End Get
End Property
Public ReadOnly Property Count As Integer
Get
Return nWords
End Get
End Property
End Class
Instrukcja using
(use
wyrażenie w języku F#) jest w rzeczywistości wygodą składniową. W czasie kompilacji kompilator języka implementuje język pośredni (IL) dla try
/finally
bloku.
Aby uzyskać więcej informacji na temat instrukcji using
, zobacz tematy Using Statement lub using Statement .
Blok Try/Finally
Jeśli język programowania nie obsługuje konstrukcji takiej jak using
instrukcja w języku C# lub Visual Basic, lub use
instrukcja w języku F#, lub jeśli nie chcesz jej używać, możesz wywołać IDisposable.Dispose implementację z finally
bloku try
/finally
instrukcji. Poniższy przykład zastępuje using
blok w poprzednim przykładzie blokiem/try``finally
.
using System;
using System.IO;
using System.Text.RegularExpressions;
public class WordCount2
{
private String filename = String.Empty;
private int nWords = 0;
private String pattern = @"\b\w+\b";
public WordCount2(string filename)
{
if (!File.Exists(filename))
throw new FileNotFoundException("The file does not exist.");
this.filename = filename;
string txt = String.Empty;
StreamReader sr = null;
try
{
sr = new StreamReader(filename);
txt = sr.ReadToEnd();
}
finally
{
if (sr != null) sr.Dispose();
}
nWords = Regex.Matches(txt, pattern).Count;
}
public string FullName
{ get { return filename; } }
public string Name
{ get { return Path.GetFileName(filename); } }
public int Count
{ get { return nWords; } }
}
open System.IO
open System.Text.RegularExpressions
type WordCount2(filename) =
let txt =
if File.Exists filename |> not then
raise (FileNotFoundException "The file does not exist.")
let sr = new StreamReader(filename)
try
sr.ReadToEnd()
finally
sr.Dispose()
let pattern = @"\b\w+\b"
let nWords = Regex.Matches(txt, pattern).Count
member _.FullName = filename
member _.Name = Path.GetFileName filename
member _.Count = nWords
Imports System.IO
Imports System.Text.RegularExpressions
Public Class WordCount
Private filename As String
Private nWords As Integer
Private pattern As String = "\b\w+\b"
Public Sub New(filename As String)
If Not File.Exists(filename) Then
Throw New FileNotFoundException("The file does not exist.")
End If
Me.filename = filename
Dim txt As String = String.Empty
Dim sr As StreamReader = Nothing
Try
sr = New StreamReader(filename)
txt = sr.ReadToEnd()
Finally
If sr IsNot Nothing Then sr.Dispose()
End Try
nWords = Regex.Matches(txt, pattern).Count
End Sub
Public ReadOnly Property FullName As String
Get
Return filename
End Get
End Property
Public ReadOnly Property Name As String
Get
Return Path.GetFileName(filename)
End Get
End Property
Public ReadOnly Property Count As Integer
Get
Return nWords
End Get
End Property
End Class
Aby uzyskać więcej informacji na try
/finally
temat wzorca, zobacz Wypróbuj... Złapać... Finally, instrukcja, try-finally, spróbuj... finally Expression lub try-finally, instrukcja.
Implementowanie interfejsu IDisposable
Należy zaimplementować IDisposable , jeśli typ używa zasobów niezarządzanych bezpośrednio lub jeśli chcesz samodzielnie korzystać z jednorazowych zasobów. Użytkownicy typu mogą wywołać implementację IDisposable.Dispose , aby zwolnić zasoby, gdy wystąpienie nie jest już potrzebne. Aby obsłużyć przypadki, w których nie można wywołać Disposemetody , należy użyć klasy pochodzącej z SafeHandle klasy w celu opakowania niezarządzanych zasobów lub przesłonić Object.Finalize metodę dla typu odwołania. W obu przypadkach należy użyć Dispose metody , aby wykonać dowolne oczyszczanie, które jest konieczne po użyciu niezarządzanych zasobów, takich jak zwalnianie, zwalnianie lub resetowanie niezarządzanych zasobów. Aby uzyskać więcej informacji na temat implementowania IDisposable.Disposemetody , zobacz przeciążenie metody Dispose(bool).
Ważne
Jeśli definiujesz klasę bazową, która używa niezarządzanych zasobów i która ma lub prawdopodobnie ma podklasy, które powinny zostać usunięte, należy zaimplementować IDisposable.Dispose metodę i podać drugie przeciążenie Dispose
elementu , zgodnie z opisem w następnej sekcji.
IDisposable i hierarchia dziedziczenia
Klasa bazowa z podklasami, która powinna być jednorazowa, musi zostać zaimplementowana IDisposable w następujący sposób. Należy użyć tego wzorca zawsze, gdy implementujesz IDisposable dowolny typ, który nie sealed
jest (NotInheritable
w Visual Basic).
Powinna ona podać jedną publiczną, niewirtuacyjną Dispose() metodę i chronioną metodę wirtualną
Dispose(Boolean disposing)
.Metoda Dispose() musi wywołać
Dispose(true)
metodę i powinna pominąć finalizację pod kątem wydajności.Typ podstawowy nie powinien zawierać żadnych finalizatorów.
Poniższy fragment kodu odzwierciedla wzorzec usuwania dla klas bazowych. Przyjęto założenie, że typ nie zastępuje Object.Finalize metody .
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
class BaseClass1 : IDisposable
{
// Flag: Has Dispose already been called?
bool disposed = false;
// Instantiate a SafeHandle instance.
SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
handle.Dispose();
// Free any other managed objects here.
//
}
disposed = true;
}
}
open Microsoft.Win32.SafeHandles
open System
type BaseClass1() =
// Flag: Has Dispose already been called?
let mutable disposed = false
// Instantiate a SafeHandle instance.
let handle = new SafeFileHandle(IntPtr.Zero, true)
interface IDisposable with
// Public implementation of Dispose pattern callable by consumers.
member this.Dispose() =
this.Dispose true
GC.SuppressFinalize this
// Implementation of Dispose pattern.
abstract Dispose: bool -> unit
override _.Dispose(disposing) =
if not disposed then
if disposing then
handle.Dispose()
// Free any other managed objects here.
disposed <- true
Imports Microsoft.Win32.SafeHandles
Imports System.Runtime.InteropServices
Class BaseClass : Implements IDisposable
' Flag: Has Dispose already been called?
Dim disposed As Boolean = False
' Instantiate a SafeHandle instance.
Dim handle As SafeHandle = New SafeFileHandle(IntPtr.Zero, True)
' Public implementation of Dispose pattern callable by consumers.
Public Sub Dispose() _
Implements IDisposable.Dispose
Dispose(disposing:=True)
GC.SuppressFinalize(Me)
End Sub
' Protected implementation of Dispose pattern.
Protected Overridable Sub Dispose(disposing As Boolean)
If disposed Then Return
If disposing Then
handle.Dispose()
' Free any other managed objects here.
'
End If
disposed = True
End Sub
End Class
Jeśli zastąpisz metodę Object.Finalize , klasa powinna zaimplementować następujący wzorzec.
using System;
class BaseClass2 : IDisposable
{
// Flag: Has Dispose already been called?
bool disposed = false;
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
// Free any other managed objects here.
//
}
// Free any unmanaged objects here.
//
disposed = true;
}
~BaseClass2()
{
Dispose(disposing: false);
}
}
open System
type BaseClass2() =
// Flag: Has Dispose already been called?
let mutable disposed = false
interface IDisposable with
// Public implementation of Dispose pattern callable by consumers.
member this.Dispose() =
this.Dispose true
GC.SuppressFinalize this
// Implementation of Dispose pattern.
abstract Dispose: bool -> unit
override _.Dispose(disposing) =
if not disposed then
if disposing then
// Free any other managed objects here.
()
// Free any unmanaged objects here.
disposed <- true
override this.Finalize() =
this.Dispose false
Class BaseClass : Implements IDisposable
' Flag: Has Dispose already been called?
Dim disposed As Boolean = False
' Public implementation of Dispose pattern callable by consumers.
Public Sub Dispose() _
Implements IDisposable.Dispose
Dispose(disposing:=True)
GC.SuppressFinalize(Me)
End Sub
' Protected implementation of Dispose pattern.
Protected Overridable Sub Dispose(disposing As Boolean)
If disposed Then Return
If disposing Then
' Free any other managed objects here.
'
End If
' Free any unmanaged objects here.
'
disposed = True
End Sub
Protected Overrides Sub Finalize()
Dispose(disposing:=False)
End Sub
End Class
Podklasy powinny implementować wzorzec jednorazowego w następujący sposób:
Muszą one zastąpić
Dispose(Boolean)
i wywołać implementację klasyDispose(Boolean)
bazowej.W razie potrzeby mogą dostarczyć finalizator. Finalizator musi wywołać metodę
Dispose(false)
.
Należy pamiętać, że klasy pochodne nie implementują interfejsu IDisposable i nie zawierają metody bez Dispose parametrów. Przesłaniają tylko metodę klasy Dispose(Boolean)
bazowej.
Poniższy fragment kodu odzwierciedla wzorzec usuwania dla klas pochodnych. Przyjęto założenie, że typ nie zastępuje Object.Finalize metody .
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
class MyDerivedClass : MyBaseClass
{
// Flag: Has Dispose already been called?
bool disposed = false;
// Instantiate a SafeHandle instance.
SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);
// Protected implementation of Dispose pattern.
protected override void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
handle.Dispose();
// Free any other managed objects here.
//
}
// Free any unmanaged objects here.
//
disposed = true;
// Call base class implementation.
base.Dispose(disposing);
}
}
open Microsoft.Win32.SafeHandles
open System
type MyDerivedClass() =
inherit MyBaseClass()
// Flag: Has Dispose already been called?
let mutable disposed = false
// Instantiate a SafeHandle instance.
let handle = new SafeFileHandle(IntPtr.Zero, true)
// Implementation of Dispose pattern.
override _.Dispose(disposing) =
if not disposed then
if disposing then
handle.Dispose()
// Free any other managed objects here.
// Free any unmanaged objects here.
disposed <- true
// Call base class implementation.
base.Dispose disposing
Imports Microsoft.Win32.SafeHandles
Imports System.Runtime.InteropServices
Class DerivedClass : Inherits BaseClass
' Flag: Has Dispose already been called?
Dim disposed As Boolean = False
' Instantiate a SafeHandle instance.
Dim handle As SafeHandle = New SafeFileHandle(IntPtr.Zero, True)
' Protected implementation of Dispose pattern.
Protected Overrides Sub Dispose(disposing As Boolean)
If disposed Then Return
If disposing Then
handle.Dispose()
' Free any other managed objects here.
'
End If
' Free any unmanaged objects here.
'
disposed = True
' Call base class implementation.
MyBase.Dispose(disposing)
End Sub
End Class
Metody
Dispose() |
Wykonuje zdefiniowane przez aplikację zadania skojarzone ze zwalnianiem lub resetowaniem zasobów niezarządzanych. |