Share via


IDisposable インターフェイス

割り当てられたアンマネージ リソースを解放するメソッドを定義します。

この型のすべてのメンバの一覧については、IDisposable メンバ を参照してください。

Public Interface IDisposable
[C#]
public interface IDisposable
[C++]
public __gc __interface IDisposable
[JScript]
public interface IDisposable

IDisposable を実装するクラス

クラス 説明
AsymmetricAlgorithm 非対称アルゴリズムのすべての実装が継承する必要がある、抽象基本クラスを表します。
BinaryReader プリミティブ データ型を特定のエンコーディングのバイナリ値として読み取ります。
BinaryWriter プリミティブ型をバイナリでストリームに書き込みます。特定のエンコーディングの文字列の書き込みをサポートします。
Brush この抽象基本クラスから派生したクラスでは、四角形、楕円、扇形、多角形、パスなどのグラフィカル形状の内部を塗りつぶすときに使用するオブジェクトを定義します。
CacheDependency キャッシュの依存関係を追跡します。追跡対象として、ファイル、ディレクトリ、アプリケーションの Cache 内にある他のオブジェクトへのキーを指定できます。このクラスは継承できません。
Component IComponent インターフェイスの基本実装を提供し、アプリケーション間でオブジェクトを共有できるようにします。
ComponentDesigner コンポーネントのデザイン モードの動作を拡張するための基本デザイナ クラス。
Container 0 個以上のコンポーネントをカプセル化します。
Control すべての ASP.NET サーバー コントロールが共有するプロパティ、メソッド、およびイベントを定義します。
CryptoAPITransform データの暗号変換を実行します。
Cursor マウス ポインタの描画に使用されるイメージを表します。
CustomLineCap ユーザー定義のカスタム ライン キャップをカプセル化します。
DesignerTransaction パフォーマンスを向上し、ほとんどの変更内容を元に戻せるようにするために、デザイン時の一連の操作をグループ化する手段を提供します。
EncoderParameter EncoderParameter オブジェクトを使用して、値の配列をイメージ エンコーダに渡すことができます。また、 EncoderParameter オブジェクトを使用して、特定のイメージ エンコーダの特定のパラメータがサポートする値のリストを受け取ることもできます。
EncoderParameters EncoderParameter オブジェクトの配列をカプセル化します。
EventHandlerList デリゲートの単純なリストを提供します。このクラスは継承できません。
Font フォント フェイス、サイズ、スタイルの各属性など、テキストの特定の書式を定義します。このクラスは継承できません。
FontCollection インストール済みおよびプライベートなフォント コレクションの基本クラスです。コレクションに含まれるフォント ファミリのリストを取得するためのメソッドを提供します。プログラム例を含む、フォントとテキストの詳細については、このドキュメントの「GDI+ マネージ クラスの使用」で「フォントとテキスト」を参照してください。
FontFamily 基本デザインが同様でスタイルが異なるタイプフェイスのグループを定義します。このクラスは継承できません。
FromBase64Transform base 64 から CryptoStream を変換します。
Graphics GDI+ 描画面をカプセル化します。このクラスは継承できません。
GraphicsPath 接続された一連の直線と曲線を表します。このクラスは継承できません。
GraphicsPathIterator GraphicsPath オブジェクト内のサブパスを反復処理し、各サブパスに含まれている図形の種類を調べることができるようにします。このクラスは継承できません。
HashAlgorithm 暗号ハッシュ アルゴリズムのすべての実装の派生元となる基本クラスを表します。
HttpApplication ASP.NET アプリケーション内のすべてのアプリケーション オブジェクトに共通のメソッド、プロパティ、およびイベントを定義します。このクラスはアプリケーションの基本クラスであり、開発者が global.asax ファイルで定義します。
Icon Windows のアイコン (オブジェクトを表すために使用される小さなビットマップ イメージ) を表します。アイコンは透明なビットマップと考えることもできますが、そのサイズはシステムによって決定されます。
Image Bitmap および Metafile の派生クラス機能を提供する抽象基本クラス。
ImageAttributes ImageAttributes オブジェクトは、レンダリング時のビットマップとメタファイルの色の操作方法に関する情報を格納します。 ImageAttributes オブジェクトは、カラー調整行列、グレースケール調整行列、ガンマ補正値、カラー マップ テーブル、色のしきい値などのカラー調整設定を保持します。

レンダリングの実行時に、色に対して修正、明度の調整、削除などの操作を実行できます。これらの操作を適用するには、 ImageAttributes オブジェクトを初期化し、 ImageAttributes オブジェクトのアドレスを Image オブジェクトのアドレスと共に、 DrawImage メソッドに渡します。

IsolatedStorageFile ファイルとディレクトリを格納している分離ストレージ領域を表します。
License すべてのライセンスの抽象 (Visual Basic では MustInherit) 基本クラスを提供します。ライセンスは、コンポーネントの特定のインスタンスに対して与えられます。
LocalizationExtenderProvider ローカリゼーション機能のデザイン時のサポートをルート デザイナに提供します。
ManagementObjectCollection WMI を通じて取得される管理オブジェクトの異なるコレクションを表します。このコレクション内のオブジェクトは、 ManagementBaseObject から派生した型のオブジェクトで、 ManagementObjectManagementClass などが含まれます。

コレクションは、 ManagementObjectSearcher オブジェクトで実行された WMI クエリの結果、または指定した型 (型を表す ManagementClass から取得される) の管理オブジェクトの列挙体になります。また、このコレクションは、指定した方法で特定の管理オブジェクトに関連付けられた管理オブジェクトのコレクションとなることもあります。この場合、コレクションは GetRelated などのメソッドで取得されます。

コレクションは、 ManagementObjectCollection.ManagementObjectEnumerator を使用してウォークすることができ、コレクション内のオブジェクトはさまざまな管理タスクで検査または使用されます。

ManagementObjectCollection.ManagementObjectEnumerator コレクションの列挙子を表します。
MarshalByValueComponent IComponent を実装し、値渡しでマーシャリングされた (シリアル化されたオブジェクトのコピーが渡された) リモート処理可能なコンポーネントの基本の実装を提供します。
Matrix ジオメトリック変換を表す 3 × 3 のアフィン行列をカプセル化します。このクラスは継承できません。
MessageEnumerator メッセージ キュー内のメッセージを列挙するための前方向カーソルを提供します。
MessageQueueEnumerator メッセージ キュー内のメッセージを列挙するための前方向カーソルを提供します。
MessageQueueTransaction メッセージ キューの内部トランザクションを提供します。
OdbcDataReader データ ソースからデータ行の前方向ストリームを読み取る方法を提供します。このクラスは継承できません。
OdbcTransaction データ ソースで作成する SQL トランザクションを表します。このクラスは継承できません。
OleDbDataReader データ ソースからデータ行の前方向ストリームを読み取る方法を提供します。このクラスは継承できません。
OleDbTransaction データ ソースで作成する SQL トランザクションを表します。このクラスは継承できません。
OracleDataReader データ ソースからデータ行の前方向ストリームを読み取る方法を提供します。このクラスは継承できません。
OracleTransaction データベースで実行するトランザクションを表します。このクラスは継承できません。
PaintEventArgs Paint イベントのデータを提供します。
Pen 直線および曲線の描画に使用するオブジェクトを定義します。このクラスは継承できません。
Region 四角形とパスで構成されるグラフィックス形状の内部を示します。このクラスは継承できません。
RegistryKey Windows レジストリのキー レベル ノードを表します。このクラスはレジストリをカプセル化します。
ResourceReader .resources ファイルとストリームを列挙し、連続したリソース名と値のペアを読み取ります。
ResourceSet ある特定のカルチャ用にローカライズされたすべてのリソースを格納します。フォールバック規則を含む他のすべてのカルチャ設定は無視されます。
ResourceWriter システムの既定の形式で、リソースを出力ファイルまたは出力ストリームに書き込みます。
ResXResourceReader XML リソース (.resx) ファイルとストリームを列挙し、連続したリソース名とリソース値のペアを読み取ります。
ResXResourceWriter XML リソース (.resx) ファイルまたは出力ストリームにリソースを書き込みます。
SearchResultCollection DirectorySearcher クエリ実行中に Active Directory 階層から返された SearchResult インスタンスを格納します。
ServicedComponent COM+ サービスを使用するすべてのクラスの基本クラスを表します。
Socket Berkeley ソケット インターフェイスを実装します。
SqlCeCommand データ ソースに対して実行する SQL ステートメントを表します。
SqlCeConnection データ ソースへの開いた接続を表します。
SqlCeDataReader データ ソースからデータ行の前方向ストリームを読み取る方法を提供します。このクラスは継承できません。
SqlCeEngine SQL Server CE エンジンのプロパティ、メソッド、および他のオブジェクトを表します。このクラスは継承できません。
SqlCeRemoteDataAccess SqlCeRemoteDataAccess オブジェクトの新しいインスタンスを初期化します。リモート データ アクセスの詳細については、SQL Server CE Books Online を参照してください。
SqlCeReplication SqlCeReplication オブジェクトの新しいインスタンスを初期化します。レプリケーションの詳細については、SQL Server Books Online を参照してください。SQL Server CE でのマージ レプリケーションの詳細については、SQL Server CE Books Online を参照してください。
SqlCeTransaction データ ソースで作成する SQL トランザクションを表します。このクラスは継承できません。
SqlDataReader SQL Server データベースから行の前方向ストリームを読み取る方法を提供します。このクラスは継承できません。
SqlTransaction SQL Server データベースで作成する Transact-SQL トランザクションを表します。このクラスは継承できません。
Stream バイト シーケンスのジェネリック ビューを提供します。
StringFormat 配置や行間などのテキスト レイアウト情報、省略記号の挿入や国別の代替の数字形式などの表示方法、および OpenType 機能をカプセル化します。このクラスは継承できません。
SymmetricAlgorithm 対称アルゴリズムのすべての実装が継承する必要がある、抽象基本クラスを表します。
TcpClient TCP ネットワーク サービスのためのクライアント接続を提供します。
TempFileCollection 一時ファイルのコレクションを表します。
TemplateEditingVerb テンプレート編集フレームを作成するデザイナ動詞を表し、テンプレート エディタだけが呼び出すことができます。
TextReader 一連の文字を読み取ることができるリーダーを表します。
TextWriter 一連の文字を書き込むことができるライタを表します。このクラスは抽象クラスです。
Timer 指定した間隔でメソッドを実行するための機構を提供します。このクラスは継承できません。
ToBase64Transform CryptoStream を base 64 に変換します。
TraceListener トレース出力およびデバッグ出力を監視するリスナの抽象 (Visual Basic では MustInherit) 基本クラスを提供します。
UdpClient ユーザー データグラム プロトコル (UDP) ネットワーク サービスを提供します。
WaitHandle 共有リソースへの排他アクセスの待機に使用するオペレーティング システム固有のオブジェクトをカプセル化します。
WebResponse URI (Uniform Resource Identifier) からの応答を利用できるようにします。これは抽象 (Visual Basic では MustInherit) クラスです。

解説

マネージ オブジェクトが使用されなくなると、同オブジェクトに割り当てられているメモリはガベージ コレクタによって自動的に解放されます。ただし、ガベージ コレクションが行われるタイミングは特定できません。また、ガベージ コレクタは、ウィンドウ ハンドルなどのアンマネージ リソースを認識せずにファイルやストリームを開きます。

ガベージ コレクタを使用して、明示的にアンマネージ リソースを解放するにはこのインターフェイスの Dispose メソッドを使用します。オブジェクトがもはや必要でない場合、オブジェクトのコンシューマはこのメソッドを呼び出します。

IDisposable インターフェイスを既存のクラスに追加することは、そのクラスのセマンティクスを変更することであるため、互換性に影響する変更点と言えます。

このインターフェイスおよび Object.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

[C#] 
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.   
    }
}

[C++] 
#using <mscorlib.dll>
#using <System.dll>

using namespace System;
using namespace System::ComponentModel;

// The following example demonstrates how to create
// a resource class that implements the IDisposable interface
// and the IDisposable.Dispose method.

// A base class that implements IDisposable.
// By implementing IDisposable, you are announcing that
// instances of this type allocate scarce resources.
public __gc class MyResource : public IDisposable {
   // Pointer to an external unmanaged resource.
   IntPtr  handle;
   // Other managed resource this class uses.
   Component*  component;
   // Track whether Dispose has been called.
   bool disposed;
public:
   // The class constructor.
   MyResource(IntPtr handle) {
      this->handle = handle;
      disposed = false;
   }

   // Implement IDisposable*
   // Do not make this method virtual.
   // A derived class should not be able to  this method.
   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);
   }

private:
   // 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.
   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(S"Kernel32")]
   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);
   }
};

[JScript] JScript のサンプルはありません。Visual Basic、C#、および C++ のサンプルを表示するには、このページの左上隅にある言語のフィルタ ボタン 言語のフィルタ をクリックします。

必要条件

名前空間: System

プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ, .NET Compact Framework - Windows CE .NET

アセンブリ: Mscorlib (Mscorlib.dll 内)

参照

IDisposable メンバ | System 名前空間