IDisposable IDisposable IDisposable IDisposable Interface

정의

관리되지 않은 리소스 해제를 위한 메커니즘을 제공합니다.Provides a mechanism for releasing unmanaged resources.

public interface class IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public interface IDisposable
type IDisposable = interface
Public Interface IDisposable
파생
특성

예제

다음 예제에서는 구현 하는 리소스 클래스를 만드는 방법의 IDisposable 인터페이스입니다.The following example demonstrates how to create a resource class that implements the IDisposable interface.

#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(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(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# destructor syntax for finalization code.
        // This destructor will run only if the Dispose method
        // does not get called.
        // It gives your base class the opportunity to finalize.
        // Do not provide destructors in types derived from this class.
        ~MyResource()
        {
            // Do not re-create Dispose clean-up code here.
            // Calling Dispose(false) is optimal in terms of
            // readability and maintainability.
            Dispose(false);
        }
    }
    public static void Main()
    {
        // Insert code here to create
        // and use the MyResource object.
    }
}
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(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(false) is optimal in terms of
         ' readability and maintainability.
         Dispose(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

설명

관리 되지 않는 리소스를 해제 하는 데이 인터페이스의 기본 사용이 됩니다.The primary use of this interface is to release unmanaged resources. 가비지 수집기는 자동으로 관리 되는 개체는 개체가 더 이상 사용 될 때 할당 된 메모리를 해제 합니다.The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. 그러나 가비지 수집이 발생 하는 경우 예측할 수 없는 합니다.However, it is not possible to predict when garbage collection will occur. 또한 가비지 수집기 알지 창 핸들, 관리 되지 않는 리소스 또는 파일 및 스트림을 엽니다.Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.

사용 하 여는 Dispose 명시적으로 가비지 수집기와 함께에서 관리 되지 않는 리소스를 해제 하려면이 인터페이스의 메서드입니다.Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. 개체의 소비자는 개체가 더 이상 필요 없는 경우이 메서드를 호출할 수 없습니다.The consumer of an object can call this method when the object is no longer needed.

경고

주요 변경 내용 추가 하는 것은 IDisposable 기존 클래스에 대 한 인터페이스입니다.It is a breaking change to add the IDisposable interface to an existing class. 형식의 기존 소비자가 호출할 수 없습니다 때문에 Dispose, 해당 형식에서 보유 하는 관리 되지 않는 리소스를 해제 됩니다 확신할 수 없습니다.Because pre-existing consumers of your type cannot call Dispose, you cannot be certain that unmanaged resources held by your type will be released.

때문에 합니다 IDisposable.Dispose 인스턴스를 소유 하는 리소스를 더 이상 필요 없는 경우 구현 형식의 소비자가 호출 되 면 관리 되는 개체에 래핑해야 하거나는 SafeHandle (권장 되는 대체) 재정의해야하는또는Object.Finalize소비자가 호출 하는 관리 되지 않는 리소스를 확보 하려면 Dispose합니다.Because the IDisposable.Dispose implementation is called by the consumer of a type when the resources owned by an instance are no longer needed, you should either wrap the managed object in a SafeHandle (the recommended alternative), or you should override Object.Finalize to free unmanaged resources in the event that the consumer forgets to call Dispose.

중요

.NET framework에서는 c + + 컴파일러 리소스의 명확한 삭제를 지원 하며 직접 구현은 허용 하지 않습니다는 Dispose 메서드.In the .NET Framework, the C++ compiler supports deterministic disposal of resources and does not allow direct implementation of the Dispose method.

방법에 대 한 자세한 내용은이 인터페이스와 Object.Finalize 메서드 사용 되 고, 참조를 가비지 수집Dispose 메서드 구현 항목.For a detailed discussion about how this interface and the Object.Finalize method are used, see the Garbage Collection and Implementing a Dispose Method topics.

IDisposable을 구현 하는 개체를 사용 하 여Using an object that implements IDisposable

앱 간단히 구현 하는 개체를 사용 하는 경우는 IDisposable 인터페이스 개체를 호출 해야 IDisposable.Dispose 사용 하 여 작업을 마쳤으면 구현 합니다.If your app simply uses an object that implements the IDisposable interface, you should call the object's IDisposable.Dispose implementation when you are finished using it. 프로그래밍 언어에 따라 두 가지 방법 중 하나에서이 수행할 수 있습니다.Depending on your programming language, you can do this in one of two ways:

  • 언어를 사용 하 여 같은 생성 합니다 using C# 및 Visual Basic의 문입니다.By using a language construct such as the using statement in C# and Visual Basic.

  • 에 대 한 호출을 래핑하여 합니다 IDisposable.Dispose 구현에는 try / finally 블록입니다.By wrapping the call to the IDisposable.Dispose implementation in a try/finally block.

참고

설명서에 대 한 구현 하는 형식을 IDisposable 사실을 확인 하 고 호출에 대 한 알림을 포함 해당 Dispose 구현 합니다.Documentation for types that implement IDisposable note that fact and include a reminder to call its Dispose implementation.

C# 및 Visual Basic Using 문The C# and Visual Basic Using statement

언어와 같은 구문을 지 원하는 경우는 를 사용 하 여 C#의 문은 하며 사용 하 여 Visual Basic의 문을 사용할 수 있습니다 명시적으로 호출 하는 대신 IDisposable.Dispose 직접.If your language supports a construct such as the using statement in C# and the Using statement in Visual Basic, you can use it instead of explicitly calling IDisposable.Dispose yourself. 다음 예제에서는 정의에서이 접근 방식을 WordCount 파일과에서 단어 개수에 대 한 정보를 유지 하는 클래스입니다.The following example uses this approach in defining a WordCount class that preserves information about a file and the number of words in it.

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; } }
}   
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

using 문은 실제로 편리한 구문입니다.The using statement is actually a syntactic convenience. 중간 언어 (IL)에 대 한 언어 컴파일러가 컴파일 타임에 구현 된 try / finally 블록입니다.At compile time, the language compiler implements the intermediate language (IL) for a try/finally block.

에 대 한 자세한 내용은 합니다 using 문을 참조는 Using 문 또는 문을 사용 하 여 항목.For more information about the using statement, see the Using Statement or using Statement topics.

Try/Finally 블록The Try/Finally block

프로그래밍 언어와 같은 생성자를 지원 하지 않는 경우는 using C# 또는 Visual Basic의 경우 문 또는 사용 하지 않으려는 경우 호출할 수 있습니다는 IDisposable.Dispose 구현을 finally 블록을 try / finally 문입니다.If your programming language does not support a construct like the using statement in C# or Visual Basic, or if you prefer not to use it, you can call the IDisposable.Dispose implementation from the finally block of a try/finally statement. 다음 예제에서는 대체 합니다 using 이전 예제에서 블록을 try / finally 블록입니다.The following example replaces the using block in the previous example with a try/finally block.

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;
      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; } }
}   
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

에 대 한 자세한 내용은 합니다 try / finally 패턴을 참조 하십시오 시도 하는 중... Catch 하는 중... Finally 문, try finally, 또는 try-finally 문합니다.For more information about the try/finally pattern, see Try...Catch...Finally Statement, try-finally, or try-finally Statement.

IDisposable 구현Implementing IDisposable

구현 해야 IDisposable 형식을 관리 되지 않는 리소스를 직접 사용 하는 경우에 합니다.You should implement IDisposable only if your type uses unmanaged resources directly. 형식의 소비자가 호출할 수 없습니다 프로그램 IDisposable.Dispose 인스턴스가 더 이상 필요 없는 경우 리소스를 해제 하려면 구현 합니다.The consumers of your type can call your IDisposable.Dispose implementation to free resources when the instance is no longer needed. 호출에 실패 하는 경우를 처리 Dispose, 클래스에서 파생을 사용 하 여 SafeHandle 재정의 해야 하거나 관리 되지 않는 리소스를 래핑하는 Object.Finalize 메서드는 참조 형식에 대 한 합니다.To handle cases in which they fail to call Dispose, you should either use a class derived from SafeHandle to wrap the unmanaged resources, or you should override the Object.Finalize method for a reference type. 두 경우 모두 사용 하 여는 Dispose 확보, 해제 또는 관리 되지 않는 리소스를 다시 설정 등의 관리 되지 않는 리소스를 사용 하 여 모든 정리 반드시 수행 하는 방법입니다.In either case, you use the Dispose method to perform whatever cleanup is necessary after using the unmanaged resources, such as freeing, releasing, or resetting the unmanaged resources.

중요

기본 클래스를 정의 하는 경우 관리 되지 않는 리소스를 사용 하는, 또는 삭제 해야 하는 서브 클래스를 포함 하는 일을 할는 구현 해야 합니다 IDisposable.Dispose 메서드는 두 번째 오버 로드를 제공 하 고 Dispose다음에 설명 된 대로 섹션입니다.If you are defining a base class that uses unmanaged resources and that either has, or is likely to have, subclasses that should be disposed, you should implement the IDisposable.Dispose method and provide a second overload of Dispose, as discussed in the next section.

IDisposable 및 상속 계층 구조IDisposable and the inheritance hierarchy

삭제 가능 해야 하는 서브 클래스를 사용 하 여 기본 클래스를 구현 해야 IDisposable 다음과 같습니다.A base class with subclasses that should be disposable must implement IDisposable as follows. 구현 될 때마다이 패턴을 사용 해야 IDisposable 없는 모든 형식에 sealed (NotInheritable Visual basic에서).You should use this pattern whenever you implement IDisposable on any type that isn't sealed (NotInheritable in Visual Basic).

  • 공용, 비가상 제공 해야 Dispose() 메서드와 보호 된 가상 Dispose(Boolean disposing) 메서드.It should provide one public, non-virtual Dispose() method and a protected virtual Dispose(Boolean disposing) method.

  • 합니다 Dispose() 메서드를 호출 해야 Dispose(true) 및 성능에 대 한 종료를 표시 하지 않아야 합니다.The Dispose() method must call Dispose(true) and should suppress finalization for performance.

  • 기본 형식은 종료자를 포함하지 않아야 합니다.The base type should not include any finalizers.

다음 코드 조각은 기본 클래스에 대 한 삭제 패턴을 반영합니다.The following code fragment reflects the dispose pattern for base classes. 형식을 재정의 하지 않는 것으로 가정 합니다 Object.Finalize 메서드.It assumes that your type does not override the Object.Finalize method.

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class BaseClass : 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(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;
   }
}
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(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

재정의 하는 경우는 Object.Finalize 메서드를 클래스에 다음 패턴을 구현 해야 합니다.If you do override the Object.Finalize method, your class should implement the following pattern.

using System;

class BaseClass : IDisposable
{
   // Flag: Has Dispose already been called?
   bool disposed = false;
   
   // Public implementation of Dispose pattern callable by consumers.
   public void Dispose()
   { 
      Dispose(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;
   }

   ~BaseClass()
   {
      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(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(False)      
   End Sub
End Class

서브 클래스는 다음과 같이 삭제 가능한 패턴을 구현해야 합니다.Subclasses should implement the disposable pattern as follows:

  • Dispose(Boolean)을 재정의하고 기본 클래스 Dispose(Boolean) 구현을override 호출해야 합니다.They must override Dispose(Boolean) and call the base class Dispose(Boolean) implementation.

  • 필요한 경우 종료자를 제공할 수 있습니다.They can provide a finalizer if needed. 종료자가 Dispose(false)을 호출해야 합니다.The finalizer must call Dispose(false).

파생된 클래스 구현 하지 않는 자체를 확인 합니다 IDisposable 인터페이스 및 매개 변수가 없는 넣지 마십시오 Dispose 메서드.Note that derived classes do not themselves implement the IDisposable interface and do not include a parameterless Dispose method. 기본 클래스 재정의 Dispose(Boolean) 메서드.They only override the base class Dispose(Boolean) method.

다음 코드는 파생된 클래스에 대 한 삭제 패턴을 반영합니다.The following code fragment reflects the dispose pattern for derived classes. 형식을 재정의 하지 않는 것으로 가정 합니다 Object.Finalize 메서드.It assumes that your type does not override the Object.Finalize method.

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class DerivedClass : BaseClass
{
   // 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);
   }
}
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

메서드

Dispose() Dispose() Dispose() Dispose()

관리되지 않는 리소스의 확보, 해제 또는 다시 설정과 관련된 애플리케이션 정의 작업을 수행합니다.Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

적용 대상

추가 정보