Object.Finalize Object.Finalize Object.Finalize Object.Finalize Method

定義

允許物件在記憶體回收進行回收之前,嘗試釋放資源並執行其他清除作業。Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.

!Object ()
~Object ();
abstract member Finalize : unit -> unit
override this.Finalize : unit -> unit
Finalize ()

範例

下列範例會確認Finalize時,覆寫的物件呼叫方法Finalize終結。The following example verifies that the Finalize method is called when an object that overrides Finalize is destroyed. 請注意,在生產環境應用程式中,Finalize會覆寫方法,以釋放這個物件所持有的 unmanaged 的資源。Note that, in a production application, the Finalize method would be overridden to release unmanaged resources held by the object. 也請注意,C# 範例會提供解構函式,而不是覆寫Finalize方法。Also note that the C# example provides a destructor instead of overriding the Finalize method.

using System;
using System.Diagnostics;

public class ExampleClass
{
   Stopwatch sw;
   
   public ExampleClass()
   {
      sw = Stopwatch.StartNew();
      Console.WriteLine("Instantiated object");
   } 

   public void ShowDuration()
   {
      Console.WriteLine("This instance of {0} has been in existence for {1}",
                        this, sw.Elapsed);
   }
   
   ~ExampleClass()
   {
      Console.WriteLine("Finalizing object");
      sw.Stop();
      Console.WriteLine("This instance of {0} has been in existence for {1}",
                        this, sw.Elapsed);
   }
}

public class Demo
{
   public static void Main()
   {
      ExampleClass ex = new ExampleClass();
      ex.ShowDuration();
   }
}
// The example displays output like the following:
//    Instantiated object
//    This instance of ExampleClass has been in existence for 00:00:00.0011060
//    Finalizing object
//    This instance of ExampleClass has been in existence for 00:00:00.0036294
Imports System.Diagnostics

Public Class ExampleClass
   Dim sw As StopWatch
   
   Public Sub New()
      sw = Stopwatch.StartNew()
      Console.WriteLine("Instantiated object")
   End Sub 

   Public Sub ShowDuration()
      Console.WriteLine("This instance of {0} has been in existence for {1}",
                        Me, sw.Elapsed)
   End Sub
   
   Protected Overrides Sub Finalize()
      Console.WriteLine("Finalizing object")
      sw.Stop()
      Console.WriteLine("This instance of {0} has been in existence for {1}",
                        Me, sw.Elapsed)
   End Sub
End Class

Module Demo
   Public Sub Main()
      Dim ex As New ExampleClass()
      ex.ShowDuration()
   End Sub
End Module
' The example displays output like the following:
'    Instantiated object
'    This instance of ExampleClass has been in existence for 00:00:00.0011060
'    Finalizing object
'    This instance of ExampleClass has been in existence for 00:00:00.0036294

如需其他範例,以覆寫Finalize方法,請參閱GC.SuppressFinalize方法。For an additional example that overrides the Finalize method, see the GC.SuppressFinalize method.

備註

Finalize方法用來在終結物件之前,目前的物件所持有的 unmanaged 資源上執行清除作業。The Finalize method is used to perform cleanup operations on unmanaged resources held by the current object before the object is destroyed. 此方法受到保護,因此只能透過此類別或衍生類別存取。The method is protected and therefore is accessible only through this class or through a derived class.

本節內容:In this section:

最終處理的運作方式How finalization works

Object類別提供任何實作Finalize方法,以及記憶體回收行程不會標記類型衍生自Object進行最終處理它們會覆寫除非Finalize方法。The Object class provides no implementation for the Finalize method, and the garbage collector does not mark types derived from Object for finalization unless they override the Finalize method.

如果型別會覆寫Finalize方法,記憶體回收行程就會將每個執行個體類型的項目加入至稱為最終處理佇列的內部結構。If a type does override the Finalize method, the garbage collector adds an entry for each instance of the type to an internal structure called the finalization queue. 完成佇列包含 managed 堆積記憶體回收行程可以回收其記憶體之前,必須執行的最終處理程式碼中的所有物件的項目。The finalization queue contains entries for all the objects in the managed heap whose finalization code must run before the garbage collector can reclaim their memory. 然後呼叫記憶體回收行程Finalize方法會自動在下列情況下:The garbage collector then calls the Finalize method automatically under the following conditions:

  • 記憶體回收行程已探索物件是無法存取,除非呼叫物件豁免的最終處理之後GC.SuppressFinalize方法。After the garbage collector has discovered that an object is inaccessible, unless the object has been exempted from finalization by a call to the GC.SuppressFinalize method.

  • 僅限.NET Framework 上,在關閉應用程式定義域,除非物件已豁免最終處理。On .NET Framework only, during shutdown of an application domain, unless the object is exempt from finalization. 在關機期間仍然可以存取的甚至是物件的完成的。During shutdown, even objects that are still accessible are finalized.

Finalize 會自動呼叫一次在給定的執行個體,除非使用一種機制,例如重新註冊的物件GC.ReRegisterForFinalizeGC.SuppressFinalize方法尚未後續呼叫。Finalize is automatically called only once on a given instance, unless the object is re-registered by using a mechanism such as GC.ReRegisterForFinalize and the GC.SuppressFinalize method has not been subsequently called.

Finalize 作業會有下列限制:Finalize operations have the following limitations:

  • 當完成項執行的確切時間是未定義。The exact time when the finalizer executes is undefined. 若要確保您類別的執行個體都會實作決定性的資源釋放Close方法,或提供IDisposable.Dispose實作。To ensure deterministic release of resources for instances of your class, implement a Close method or provide a IDisposable.Dispose implementation.

  • 即使一個物件參考其他兩個物件的完成項不保證任何特定順序執行。The finalizers of two objects are not guaranteed to run in any specific order, even if one object refers to the other. 也就是說,如果物件 A 會有物件 B 的參考,而且兩者都有完成項,物件 B 可能已完成的物件的完成項開始時。That is, if Object A has a reference to Object B and both have finalizers, Object B might have already been finalized when the finalizer of Object A starts.

  • 未指定在其執行完成項執行緒。The thread on which the finalizer runs is unspecified.

Finalize方法可能不會執行到完成為止,或可能完全無法執行下列的例外情況下:The Finalize method might not run to completion or might not run at all under the following exceptional circumstances:

  • 如果另一個完成項會無限期地封鎖 (進入無限迴圈,會嘗試取得鎖定,它可能永遠不會取得,等等)。If another finalizer blocks indefinitely (goes into an infinite loop, tries to obtain a lock it can never obtain, and so on). 因為執行階段嘗試執行完成項完成時,其他完成項可能不會呼叫如果完成項區塊無限期。Because the runtime tries to run finalizers to completion, other finalizers might not be called if a finalizer blocks indefinitely.

  • 如果處理程序結束,而不讓執行階段清除。If the process terminates without giving the runtime a chance to clean up. 在此情況下,執行階段的第一次通知程序終止的是 DLL_PROCESS_DETACH 通知。In this case, the runtime's first notification of process termination is a DLL_PROCESS_DETACH notification.

執行階段會繼續在關機期間完成物件,只有當最終處理物件的數目會繼續減少時。The runtime continues to finalize objects during shutdown only while the number of finalizable objects continues to decrease.

如果Finalize或 覆寫Finalize擲回例外狀況和執行階段不會覆寫預設原則的應用程式所裝載,因此執行階段終止程序並沒有作用try / finally區塊或執行完成項。If Finalize or an override of Finalize throws an exception, and the runtime is not hosted by an application that overrides the default policy, the runtime terminates the process and no active try/finally blocks or finalizers are executed. 此行為可確保處理程序完整性,如果完成項無法釋放或終結資源。This behavior ensures process integrity if the finalizer cannot free or destroy resources.

覆寫 Finalize 方法Overriding the Finalize method

您應該覆寫Finalize類別使用 unmanaged 的資源,例如檔案控制代碼或必須發行時使用這些 managed 的物件會在記憶體回收期間捨棄的資料庫連接。You should override Finalize for a class that uses unmanaged resources, such as file handles or database connections that must be released when the managed object that uses them is discarded during garbage collection. 您不應該實作Finalize方法受管理物件,因為記憶體回收行程自動釋放 managed 的資源。You shouldn't implement a Finalize method for managed objects because the garbage collector releases managed resources automatically.

重要

如果SafeHandle都有提供物件,包裝您的 unmanaged 的資源,建議的替代做法是實作使用安全控制代碼的處置模式,並不會覆寫FinalizeIf a SafeHandle object is available that wraps your unmanaged resource, the recommended alternative is to implement the dispose pattern with a safe handle and not override Finalize. 如需詳細資訊,請參閱 < SafeHandle 替代方法一節。For more information, see The SafeHandle alternative section.

Object.Finalize方法則會根據預設,不執行任何動作,但您應該覆寫Finalize才有必要,而且只釋放 unmanaged 的資源。The Object.Finalize method does nothing by default, but you should override Finalize only if necessary, and only to release unmanaged resources. 回收記憶體,通常需要更長,如果在執行最終處理作業,因為它需要至少兩個記憶體回收。Reclaiming memory tends to take much longer if a finalization operation runs, because it requires at least two garbage collections. 此外,您應該覆寫Finalize方法參考類型才。In addition, you should override the Finalize method for reference types only. Common language runtime 只完成參考型別。The common language runtime only finalizes reference types. 它會忽略在實值型別上的完成項。It ignores finalizers on value types.

範圍Object.Finalize方法是protectedThe scope of the Object.Finalize method is protected. 當您在類別中覆寫方法時,您應該維護這個限定的範圍。You should maintain this limited scope when you override the method in your class. 藉由讓保持Finalize受保護的方法,防止使用者從呼叫物件的應用程式的Finalize直接方法。By keeping a Finalize method protected, you prevent users of your application from calling an object's Finalize method directly.

每個實作Finalize衍生的型別必須呼叫其基底類型實作FinalizeEvery implementation of Finalize in a derived type must call its base type's implementation of Finalize. 這是這類應用程式碼允許呼叫的唯一情況FinalizeThis is the only case in which application code is allowed to call Finalize. 物件的Finalize方法不應該在其基底類別以外的其他任何物件上呼叫方法。An object's Finalize method shouldn't call a method on any objects other than that of its base class. 這是因為被呼叫的其他物件收集同時作為呼叫物件時,例如在通用語言執行階段關機的情況下。This is because the other objects being called could be collected at the same time as the calling object, such as in the case of a common language runtime shutdown.

注意

C# 編譯器不允許您覆寫Finalize方法。The C# compiler does not allow you to override the Finalize method. 相反地,您提供完成項方法是實作解構函式為您的類別。Instead, you provide a finalizer by implementing a destructor for your class. C# 解構函式會自動呼叫其基底類別解構函式。A C# destructor automatically calls the destructor of its base class.

視覺化C++也提供自己的語法,來實作Finalize方法。Visual C++ also provides its own syntax for implementing the Finalize method. 如需詳細資訊,請參閱 < 解構函式和完成項 > 一節How to:定義和使用類別和結構 (C++/CLI)For more information, see the "Destructors and finalizers" section of How to: Define and Consume Classes and Structs (C++/CLI).

因為記憶體回收是不具決定性,所以您不知道記憶體回收行程執行完成時。Because garbage collection is non-deterministic, you do not know precisely when the garbage collector performs finalization. 若要釋出資源立即執行,您也可以選擇實作處置模式IDisposable介面。To release resources immediately, you can also choose to implement the dispose pattern and the IDisposable interface. IDisposable.Dispose實作可以呼叫您類別的取用者釋放 unmanaged 的資源,而且您可以使用Finalize方法來釋放 unmanaged 的資源的情況Dispose不會呼叫方法。The IDisposable.Dispose implementation can be called by consumers of your class to free unmanaged resources, and you can use the Finalize method to free unmanaged resources in the event that the Dispose method is not called.

Finalize 之後它已清除記憶體回收期間,可能需要幾乎任何動作,包括 resurrecting 物件 (也就,讓物件可存取一次)。Finalize can take almost any action, including resurrecting an object (that is, making the object accessible again) after it has been cleaned up during garbage collection. 不過,該物件可以只復活一次;Finalize和物件上無法呼叫記憶體回收期間。However, the object can only be resurrected once; Finalize cannot be called on resurrected objects during garbage collection.

SafeHandle 替代方法The SafeHandle alternative

建立可靠的完成項通常很困難,因為您不能假設您的應用程式的狀態相關,而且這類未處理系統例外狀況OutOfMemoryExceptionStackOverflowException終止完成項。Creating reliable finalizers is often difficult, because you cannot make assumptions about the state of your application, and because unhandled system exceptions such as OutOfMemoryException and StackOverflowException terminate the finalizer. 而不是實作您類別的完成項,表示釋放 unmanaged 的資源,您可以使用衍生自物件System.Runtime.InteropServices.SafeHandle類別來包裝 unmanaged 的資源,,然後再實作處置模式,而不需要完成項。Instead of implementing a finalizer for your class to release unmanaged resources, you can use an object that is derived from the System.Runtime.InteropServices.SafeHandle class to wrap your unmanaged resources, and then implement the dispose pattern without a finalizer. .NET Framework 提供的下列類別Microsoft.Win32命名空間衍生自System.Runtime.InteropServices.SafeHandle:The .NET Framework provides the following classes in the Microsoft.Win32 namespace that are derived from System.Runtime.InteropServices.SafeHandle:

下列範例會使用處置模式使用安全控制代碼,而不是覆寫Finalize方法。The following example uses the dispose pattern with safe handles instead of overriding the Finalize method. 它會定義FileAssociation類別,包裝的應用程式會處理具有特定副檔名的檔案相關的登錄資訊。It defines a FileAssociation class that wraps registry information about the application that handles files with a particular file extension. 傳回兩個登錄控制代碼out由 Windows 參數RegOpenKeyEx函式呼叫會傳遞至SafeRegistryHandle建構函式。The two registry handles returned as out parameters by Windows RegOpenKeyEx function calls are passed to the SafeRegistryHandle constructor. 受保護的型別Dispose然後方法會呼叫SafeRegistryHandle.Dispose方法來釋放這些兩個控制代碼。The type's protected Dispose method then calls the SafeRegistryHandle.Dispose method to free these two handles.

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

public class FileAssociationInfo : IDisposable
{
   // Private variables.
   private String ext;
   private String openCmd;
   private String args;
   private SafeRegistryHandle hExtHandle, hAppIdHandle;

   // Windows API calls.
   [DllImport("advapi32.dll", CharSet= CharSet.Auto, SetLastError=true)]
   private static extern int RegOpenKeyEx(IntPtr hKey, 
                  String lpSubKey, int ulOptions, int samDesired,
                  out IntPtr phkResult);
   [DllImport("advapi32.dll", CharSet= CharSet.Unicode, EntryPoint = "RegQueryValueExW",
              SetLastError=true)]
   private static extern int RegQueryValueEx(IntPtr hKey,
                  string lpValueName, int lpReserved, out uint lpType, 
                  string lpData, ref uint lpcbData);   
   [DllImport("advapi32.dll", SetLastError = true)]
   private static extern int RegSetValueEx(IntPtr hKey, [MarshalAs(UnmanagedType.LPStr)] string lpValueName,
                  int Reserved, uint dwType, [MarshalAs(UnmanagedType.LPStr)] string lpData,
                  int cpData);
   [DllImport("advapi32.dll", SetLastError=true)]
   private static extern int RegCloseKey(UIntPtr hKey);

   // Windows API constants.
   private const int HKEY_CLASSES_ROOT = unchecked((int) 0x80000000);
   private const int ERROR_SUCCESS = 0;

    private const int KEY_QUERY_VALUE = 1;
    private const int KEY_SET_VALUE = 0x2;
   
   private const uint REG_SZ = 1;
   
   private const int MAX_PATH = 260;
   
   public FileAssociationInfo(String fileExtension)
   {
      int retVal = 0;
      uint lpType = 0;
                  
      if (!fileExtension.StartsWith("."))
             fileExtension = "." + fileExtension;
      ext = fileExtension;
       
      IntPtr hExtension = IntPtr.Zero;
      // Get the file extension value.
      retVal = RegOpenKeyEx(new IntPtr(HKEY_CLASSES_ROOT), fileExtension, 0, KEY_QUERY_VALUE, out hExtension);
      if (retVal != ERROR_SUCCESS) 
         throw new Win32Exception(retVal);
      // Instantiate the first SafeRegistryHandle.
      hExtHandle = new SafeRegistryHandle(hExtension, true);
      
      string appId = new string(' ', MAX_PATH);
      uint appIdLength = (uint) appId.Length;
      retVal = RegQueryValueEx(hExtHandle.DangerousGetHandle(), String.Empty, 0, out lpType, appId, ref appIdLength);
      if (retVal != ERROR_SUCCESS)
         throw new Win32Exception(retVal);
      // We no longer need the hExtension handle.
      hExtHandle.Dispose();

      // Determine the number of characters without the terminating null.
      appId = appId.Substring(0, (int) appIdLength / 2 - 1) + @"\shell\open\Command";

      // Open the application identifier key.
      string exeName = new string(' ', MAX_PATH);
      uint exeNameLength = (uint) exeName.Length;
      IntPtr hAppId;
      retVal = RegOpenKeyEx(new IntPtr(HKEY_CLASSES_ROOT), appId, 0, KEY_QUERY_VALUE | KEY_SET_VALUE,
                            out hAppId);
       if (retVal != ERROR_SUCCESS) 
         throw new Win32Exception(retVal);

      // Instantiate the second SafeRegistryHandle.
      hAppIdHandle = new SafeRegistryHandle(hAppId, true);

      // Get the executable name for this file type.
      string exePath = new string(' ', MAX_PATH);
      uint exePathLength = (uint) exePath.Length;
      retVal = RegQueryValueEx(hAppIdHandle.DangerousGetHandle(), String.Empty, 0, out lpType, exePath, ref exePathLength);
      if (retVal != ERROR_SUCCESS)
         throw new Win32Exception(retVal);
           
      // Determine the number of characters without the terminating null.
      exePath = exePath.Substring(0, (int) exePathLength / 2 - 1);
      // Remove any environment strings.
      exePath = Environment.ExpandEnvironmentVariables(exePath);

      int position = exePath.IndexOf('%');
      if (position >= 0) {
         args = exePath.Substring(position);
         // Remove command line parameters ('%0', etc.).
         exePath = exePath.Substring(0, position).Trim();
      }
      openCmd = exePath;   
   }

   public String Extension
   { get { return ext; } }
   
   public String Open
   { get { return openCmd; } 
     set {
        if (hAppIdHandle.IsInvalid | hAppIdHandle.IsClosed)
           throw new InvalidOperationException("Cannot write to registry key."); 
        if (! File.Exists(value)) {
           string message = String.Format("'{0}' does not exist", value);
           throw new FileNotFoundException(message); 
        }
        string cmd = value + " %1";
        int retVal = RegSetValueEx(hAppIdHandle.DangerousGetHandle(), String.Empty, 0, 
                                   REG_SZ, value, value.Length + 1);
        if (retVal != ERROR_SUCCESS)
           throw new Win32Exception(retVal);                          
     } }
   
   public void Dispose() 
   {
      Dispose(true);
      GC.SuppressFinalize(this);
   }   
   
   protected void Dispose(bool disposing)
   {
      // Ordinarily, we release unmanaged resources here; 
      // but all are wrapped by safe handles.
      
      // Release disposable objects.
      if (disposing) {
         if (hExtHandle != null) hExtHandle.Dispose();
         if (hAppIdHandle != null) hAppIdHandle.Dispose();
      }
   }
}
Imports Microsoft.Win32.SafeHandles
Imports System
Imports System.ComponentModel
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Text

Public Class FileAssociationInfo : Implements IDisposable
   ' Private variables.
   Private ext As String
   Private openCmd As String
   Private args As String
   Private hExtHandle, hAppIdHandle As SafeRegistryHandle

   ' Windows API calls.
   Private Declare Unicode Function RegOpenKeyEx Lib"advapi32.dll" _
                   Alias "RegOpenKeyExW" (hKey As IntPtr, lpSubKey As String, _
                   ulOptions As Integer, samDesired As Integer, _
                   ByRef phkResult As IntPtr) As Integer
   Private Declare Unicode Function RegQueryValueEx Lib "advapi32.dll" _
                   Alias "RegQueryValueExW" (hKey As IntPtr, _
                   lpValueName As String, lpReserved As Integer, _
                   ByRef lpType As UInteger, lpData As String, _
                   ByRef lpcbData As UInteger) As Integer   
   Private Declare Function RegSetValueEx Lib "advapi32.dll" _
                  (hKey As IntPtr, _
                  <MarshalAs(UnmanagedType.LPStr)> lpValueName As String, _
                  reserved As Integer, dwType As UInteger, _
                  <MarshalAs(UnmanagedType.LPStr)> lpData As String, _
                  cpData As Integer) As Integer 
   Private Declare Function RegCloseKey Lib "advapi32.dll" _
                  (hKey As IntPtr) As Integer

   ' Windows API constants.
   Private Const HKEY_CLASSES_ROOT As Integer = &h80000000
   Private Const ERROR_SUCCESS As Integer = 0

   Private Const KEY_QUERY_VALUE As Integer = 1
   Private Const KEY_SET_VALUE As Integer = &h2
   
   Private REG_SZ As UInteger = 1
   
   Private Const MAX_PATH As Integer  = 260
   
   Public Sub New(fileExtension As String)
      Dim retVal As Integer = 0
      Dim lpType As UInteger = 0
                  
      If Not fileExtension.StartsWith(".") Then 
         fileExtension = "." + fileExtension
      End If   
      ext = fileExtension
       
      Dim hExtension As IntPtr = IntPtr.Zero
      ' Get the file extension value.
      retVal = RegOpenKeyEx(New IntPtr(HKEY_CLASSES_ROOT), fileExtension, 0, 
                            KEY_QUERY_VALUE, hExtension)
      if retVal <> ERROR_SUCCESS Then 
         Throw New Win32Exception(retVal)
      End If  
      ' Instantiate the first SafeRegistryHandle.
      hExtHandle = New SafeRegistryHandle(hExtension, True)
      
      Dim appId As New String(" "c, MAX_PATH)
      Dim appIdLength As UInteger = CUInt(appId.Length)
      retVal = RegQueryValueEx(hExtHandle.DangerousGetHandle(), String.Empty, _
                               0, lpType, appId, appIdLength)
      if retVal <> ERROR_SUCCESS Then
         Throw New Win32Exception(retVal)
      End If   
      ' We no longer need the hExtension handle.
      hExtHandle.Dispose()

      ' Determine the number of characters without the terminating null.
      appId = appId.Substring(0, CInt(appIdLength) \ 2 - 1) + "\shell\open\Command"

      ' Open the application identifier key.
      Dim exeName As New string(" "c, MAX_PATH)
      Dim exeNameLength As UInteger = CUInt(exeName.Length)
      Dim hAppId As IntPtr
      retVal = RegOpenKeyEx(New IntPtr(HKEY_CLASSES_ROOT), appId, 0, 
                            KEY_QUERY_VALUE Or KEY_SET_VALUE, hAppId)
      If retVal <> ERROR_SUCCESS Then 
         Throw New Win32Exception(retVal)
      End If   

      ' Instantiate the second SafeRegistryHandle.
      hAppIdHandle = New SafeRegistryHandle(hAppId, True)

      ' Get the executable name for this file type.
      Dim exePath As New string(" "c, MAX_PATH)
      Dim exePathLength As UInteger = CUInt(exePath.Length)
      retVal = RegQueryValueEx(hAppIdHandle.DangerousGetHandle(), _
                               String.Empty, 0, lpType, exePath, exePathLength)
      If retVal <> ERROR_SUCCESS Then
         Throw New Win32Exception(retVal)
      End If     
      ' Determine the number of characters without the terminating null.
      exePath = exePath.Substring(0, CInt(exePathLength) \ 2 - 1)
  
      exePath = Environment.ExpandEnvironmentVariables(exePath)
      Dim position As Integer = exePath.IndexOf("%"c)
      If position >= 0 Then
         args = exePath.Substring(position)
         ' Remove command line parameters ('%0', etc.).
         exePath = exePath.Substring(0, position).Trim()
      End If   
      openCmd = exePath
   End Sub

   Public ReadOnly Property Extension As String
      Get
         Return ext
      End Get
   End Property
   
   Public Property Open As String
      Get
         Return openCmd
      End Get    
      Set 
        If hAppIdHandle.IsInvalid Or hAppIdHandle.IsClosed Then
           Throw New InvalidOperationException("Cannot write to registry key.")
        End If    
        If Not File.Exists(value) Then
           Dim message As String = String.Format("'{0}' does not exist", value)
           Throw New FileNotFoundException(message) 
        End If
        Dim cmd As String = value + " %1"
        Dim retVal As Integer = RegSetValueEx(hAppIdHandle.DangerousGetHandle(), String.Empty, 0, 
                                              REG_SZ, value, value.Length + 1)
        If retVal <> ERROR_SUCCESS Then 
           Throw New Win32Exception(retVal)
        End If                             
      End Set
   End Property   
   
   Public Sub Dispose() _
      Implements IDisposable.Dispose 
      Dispose(true)
      GC.SuppressFinalize(Me)
   End Sub   
   
   Protected Sub Dispose(disposing As Boolean)
      ' Ordinarily, we release unmanaged resources here 
      ' but all are wrapped by safe handles.
      
      ' Release disposable objects.
      If disposing Then
         If hExtHandle IsNot Nothing Then hExtHandle.Dispose()
         If hAppIdHandle IsNot Nothing Then hAppIdHandle.Dispose()
      End If
   End Sub
End Class

適用於

另請參閱