Object.Finalize 方法

定義

允許物件在記憶體回收進行回收之前,嘗試釋放資源並執行其他清除作業。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 方法,以釋放物件所持有的非受控資源。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 方法是用來在終結物件之前,對目前物件所持有的非受控資源執行清除作業。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.ReRegisterForFinalize 的機制重新註冊,而且後續並未呼叫 GC.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 的參考,而且兩者都有完成項,則當物件 A 的 finalizer 開始時,物件 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,例如,在垃圾收集期間捨棄使用它們的 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. 您不應該針對 managed 物件執行 Finalize 方法,因為垃圾收集行程會自動釋放受管理的資源。You shouldn't implement a Finalize method for managed objects because the garbage collector releases managed resources automatically.

重要

如果 SafeHandle 物件可包裝您的非受控資源,建議的替代做法是使用安全控制碼來實作為處置模式,而不要覆寫 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,並僅釋放非受控資源。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. 通用語言執行時間只會完成參考型別。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. 這是允許應用程式代碼呼叫 Finalize的唯一案例。This 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. 這是因為所呼叫的其他物件可以與呼叫物件同時收集,例如在 common language runtime 關閉的情況下。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. 如需詳細資訊,請參閱如何:定義和使用類別和結構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 實作為釋放非受控資源,而且您可以使用 Finalize 方法,在未呼叫 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. 不過,物件只能 isdefunct 一次;在垃圾收集期間,無法在 isdefunct 物件上呼叫 FinalizeHowever, 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. 您可以使用衍生自 System.Runtime.InteropServices.SafeHandle 類別的物件來包裝非受控資源,然後在沒有完成項的情況下執行 dispose 模式,而不是為您的類別執行完成項來釋放非受控資源。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:

下列範例會使用dispose 模式搭配安全控制碼,而不是覆寫 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. 由 Windows RegOpenKeyEx函式呼叫傳回做為 out 參數的兩個登錄控制碼會傳遞給 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.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

適用於

另請參閱