IDisposable.Dispose メソッドとは? わかりやすく解説

Weblio 辞書 > コンピュータ > .NET Framework クラス ライブラリ リファレンス > IDisposable.Dispose メソッドの意味・解説 

IDisposable.Dispose メソッド

アンマネージ リソース解放およびリセット関連付けられているアプリケーション定義のタスク実行します

名前空間: System
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

解説解説

このメソッドは、このインターフェイス実装するクラスインスタンス保持するファイルストリームハンドルなどのアンマネージ リソース閉じた解放したりする場合使用します通常、このメソッドは、オブジェクト保持するリソース解放や、オブジェクト再利用準備関連付けられたすべてのタスク使用されます。

メモ重要 :

C++ プログラマは、「Destructors and Finalizers in Visual C++」を参照してください.NET Framework Version 2.0場合C++ コンパイラは、リソース確定的な破棄実装するためのサポート提供しますが、Dispose メソッド直接的な実装許可しません。

このメソッド実装する場合、この呼び出しコンテインメント階層全体伝達することによって、保持しているリソースがすべて確実に解放されるようにする必要があります。たとえば、オブジェクト A がオブジェクト B を割り当てオブジェクト B がオブジェクト C を割り当てると、A の Dispose 実装は B の Dispose呼び出し、さらにこれが C の Dispose呼び出す必要があります。各オブジェクトはさらに、それぞれの基本クラスIDisposable実装する場合は、同クラスDispose メソッド呼び出す必要があります

オブジェクトDispose メソッド複数呼び出され場合、そのオブジェクト最初呼び出し以外は無視する必要がありますオブジェクトDispose メソッド複数呼び出す場合は、このオブジェクトから例外スローないようにします。Dispose 以外のインスタンス メソッドでは、リソースが既に破棄されている場合に、ObjectDisposedException をスローできます

割り当てられている状態と解放されている状態を示すために、リソース種類に応じて特別な規則使用する場合あります。たとえば、ストリーム クラス従来からオープン状態またはクローズ態となされてます。そのような規則を持つクラス実装する場合Dispose メソッド呼び出すパブリック メソッドに、Close などのカスタム名を付けて実装することもできます

Dispose メソッド明示的に呼び出す必要があるため、IDisposable実装するオブジェクトは、Dispose呼び出されなかった場合リソース解放処理するファイナライザ実装する必要があります既定では、メモリを再要求する前にガベージ コレクタオブジェクトファイナライザ自動的に呼び出します。ただし、Dispose メソッド呼び出されていれば破棄されオブジェクトファイナライザガベージ コレクタ呼び出す必要は通常ありません。自動終了されないようにするには、Dispose 実装で GC.SuppressFinalize メソッド呼び出します。

ファイナライザ実装Dispose メソッド詳細については、GC クラス、Object.Finalize メソッド、および アンマネージ リソースクリーンアップするための Finalize および Dispose実装 の各トピック参照してください

使用例使用例
Imports System
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.
      Private 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
         End If
         disposed = True
      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
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.
        private 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;            
            }
            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.   
    }
}
#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();
}
import System.*;
import 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 static class
 MyResource implements 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 boolean disposed = false;

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

        // 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

        // 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.
        private void Dispose(boolean 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;
            }
            disposed = true;
        } //Dispose

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

        // Use J# 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.
        public void finalize() 
        {
            // Do not re-create Dispose clean-up code here.
            // Calling Dispose(false) is optimal in terms of
            // readability and maintainability.
            Dispose(false);
            try {
                super.finalize();
            }
            catch(System.Exception e ) {
            }
        } //finalize
    } //MyResource   
   
    public static void main(String[]
 args)
    {
        // Insert code here to create
        // and use the MyResource object.      
    } //main
} //DisposeExample 
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「IDisposable.Dispose メソッド」の関連用語

IDisposable.Dispose メソッドのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



IDisposable.Dispose メソッドのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.

©2024 GRAS Group, Inc.RSS