System.Object.Finalize 메서드

이 문서에서는 이 API에 대한 참조 설명서에 대한 추가 설명서를 제공합니다.

Finalize 메서드는 개체가 제거되기 전에 현재 개체가 보유한 관리되지 않는 리소스에 대해 클린up 작업을 수행하는 데 사용됩니다. 이 메서드는 보호되므로 이 클래스를 통해서만 또는 파생 클래스를 통해서만 액세스할 수 있습니다.

종료 작동 방식

클래스는 Object 메서드에 대한 구현을 Finalize 제공하지 않으며, 메서드를 재정의하지 않는 한 가비지 수집기는 종료를 위해 파생된 Object 형식을 Finalize 표시하지 않습니다.

형식이 메서드를 재정 Finalize 의하는 경우 가비지 수집기는 형식의 각 인스턴스에 대한 항목을 종료 큐라는 내부 구조에 추가합니다. 종료 큐에는 가비지 수집기가 메모리를 회수하기 전에 종료 코드를 실행해야 하는 관리되는 힙의 모든 개체에 대한 항목이 포함됩니다. 가비지 수집기는 다음 조건에서 메서드를 자동으로 호출 Finalize 합니다.

  • 메서드를 호출하여 개체를 종료에서 제외하지 않는 한 가비지 수집기에서 개체에 액세스할 수 없음을 GC.SuppressFinalize 발견한 후에는 개체에 액세스할 수 없습니다.
  • .NET framework만, 애플리케이션 도메인을 종료 하는 동안 없으면 개체를 종료 한 예외로 지정 합니다. 종료하는 동안 여전히 액세스할 수 있는 개체도 종료됩니다.

Finalize 와 같은 GC.ReRegisterForFinalize 메커니즘을 사용하여 개체를 다시 등록하고 메서드가 이후에 호출되지 않는 한 지정된 인스턴스에서 GC.SuppressFinalize 한 번만 자동으로 호출됩니다.

Finalize 작업에는 다음과 같은 제한 사항이 있습니다.

  • 종료자가 실행되는 정확한 시간은 정의되지 않습니다. 클래스 인스턴스에 대한 리소스의 결정적 릴리스를 보장하려면 메서드를 Close 구현하거나 구현을 IDisposable.Dispose 제공합니다.
  • 한 개체가 다른 개체를 참조하더라도 두 개체의 종료자는 특정 순서로 실행되지 않습니다. 즉, 개체 A에 개체 B에 대한 참조가 있고 둘 다 종료자가 있는 경우 개체 A의 종료자가 시작될 때 개체 B가 이미 종료되었을 수 있습니다.
  • 종료자가 실행되는 스레드는 지정되지 않습니다.

메서드가 Finalize 완료될 때 실행되지 않거나 다음과 같은 예외적인 상황에서 전혀 실행되지 않을 수 있습니다.

  • 다른 종료자가 무기한으로 차단되는 경우(무한 루프로 들어가서 가져올 수 없는 잠금을 가져오려고 시도합니다. 등). 런타임이 완료될 때 종료자를 실행하려고 하기 때문에 종료자가 무기한 차단되면 다른 종료자가 호출되지 않을 수 있습니다.
  • 런타임에 클린 기회를 주지 않고 프로세스가 종료되는 경우 이 경우 런타임의 첫 번째 프로세스 종료 알림은 DLL_PROCESS_DETACH 알림입니다.

종료할 수 있는 개체의 수가 계속 감소하는 동안에만 런타임이 종료하는 동안에만 개체를 계속 종료합니다.

하는 경우 Finalize 또는 재정의 Finalize 예외를 throw 하 고 런타임이 기본 정책을 재정의 하는 애플리케이션에서 호스트 되지 않는, 프로세스 및 없는 활성 런타임이 종료 try/finally 블록 또는 종료자 실행 됩니다. 이 동작은 종료자가 리소스를 해제하거나 제거할 수 없는 경우 프로세스 무결성을 보장합니다.

Finalize 메서드 재정의

가비지 수집 중에 파일 핸들 또는 이를 사용하는 관리되는 개체가 해제될 때 해제해야 하는 데이터베이스 연결 같은 관리되지 않는 리소스카드를 사용하는 클래스에 대해 재정 Finalize 의해야 합니다. 가비지 수집기가 관리되는 리소스를 Finalize 자동으로 해제하므로 관리되는 개체에 대한 메서드를 구현해서는 안 됩니다.

Important

관리되지 않는 리소스를 SafeHandle 래핑하는 개체를 사용할 수 있는 경우 재정의하지 않고 Finalize안전한 핸들로 삭제 패턴을 구현하는 것이 좋습니다. 자세한 내용은 금고 대체 섹션을 참조하세요.

이 메서드는 Object.Finalize 기본적으로 아무 것도 수행하지 않지만 필요한 경우에만 재정 Finalize 의하고 관리되지 않는 리소스를 해제해야 합니다. 메모리 회수는 종료 작업이 실행되는 경우 가비지 수집이 두 개 이상 필요하기 때문에 훨씬 더 오래 걸리는 경향이 있습니다. 또한 참조 형식에 대해서만 메서드를 재정의 Finalize 해야 합니다. 공용 언어 런타임은 참조 형식만 완료합니다. 값 형식에 대한 종료자는 무시됩니다.

메서드의 범위는 Object.Finalize .입니다 protected. 클래스에서 메서드를 재정의할 때 이 제한된 범위를 기본 합니다. 유지 하 여는 Finalize 개체의 호출에서 애플리케이션의 사용자를 방지 보호 되는 메서드, Finalize 메서드를 직접.

파생 형식의 Finalize 모든 구현은 기본 형식의 구현 Finalize을 호출해야 합니다. 이 애플리케이션에서 코드를 호출할 수는 유일한 경우는 Finalize합니다. 개체의 Finalize 메서드는 기본 클래스 이외의 개체에서 메서드를 호출하면 안 됩니다. 이는 공용 언어 런타임 종료의 경우와 같이 호출되는 다른 개체를 호출 개체와 동시에 수집할 수 있기 때문입니다.

참고 항목

C# 컴파일러에서는 메서드를 재정의 Finalize 할 수 없습니다. 대신 클래스에 대한 소멸자를 구현하여 종료자를 제공합니다. C# 소멸자가 해당 기본 클래스의 소멸자를 자동으로 호출합니다.

또한 Visual C++는 메서드를 구현하기 Finalize 위한 고유한 구문을 제공합니다. 자세한 내용은 방법: 클래스 및 구조체 정의 및 사용(C++/CLI)"소멸자 및 종료자" 섹션을 참조하세요.

가비지 수집은 비결정적이므로 가비지 수집기가 종료를 수행하는 시기를 정확하게 알 수 없습니다. 리소스를 즉시 해제하려면 삭제 패턴IDisposable 인터페이스를 구현하도록 선택할 수도 있습니다. 구현은 IDisposable.Dispose 클래스의 소비자가 관리되지 않는 리소스를 해제하도록 호출할 수 있으며, 메서드를 Finalize 사용하여 메서드가 호출되지 않은 경우 Dispose 관리되지 않는 리소스를 해제할 수 있습니다.

Finalize가비지 수집 중에 개체를 클린 후 개체를 다시 액세스할 수 있도록 하는 작업을 포함하여 거의 모든 작업을 수행할 수 있습니다. 그러나 개체는 한 번만 부활할 수 있습니다. Finalize 가비지 수집 중에는 부활된 개체에 대해 호출할 수 없습니다.

금고 대체 항목

신뢰할 수 있는 종료자를 만들기 어렵습니다, 이므로 같은 시스템 예외를 처리 되지 않은 애플리케이션의 상태에 대 한 가정을 변경할 수 없으므로 OutOfMemoryExceptionStackOverflowException 종료자를 종료 합니다. 클래스에서 관리되지 않는 리소스를 해제하기 위해 종료자를 구현하는 대신 클래스에서 System.Runtime.InteropServices.SafeHandle 파생된 개체를 사용하여 관리되지 않는 리소스를 래핑한 다음 종료자 없이 삭제 패턴을 구현할 수 있습니다. .NET Framework는 네임스페이스에서 Microsoft.Win32 파생된 다음 클래스를 System.Runtime.InteropServices.SafeHandle제공합니다.

다음 예제에서는 메서드를 재정의하는 Finalize 대신 안전한 핸들과 함께 dispose 패턴을 사용합니다. 정의 FileAssociation 특정 파일 확장명을 사용 하 여 파일을 처리 하는 애플리케이션에 대 한 레지스트리 정보를 래핑하는 클래스입니다. Windows RegOpenKeyEx 함수 호출에 의해 매개 변수로 out 반환된 SafeRegistryHandle 두 개의 레지스트리 핸들이 생성자에 전달됩니다. 그런 다음 형식의 보호된 메서드는 Dispose 메서드를 SafeRegistryHandle.Dispose 호출하여 이러한 두 핸들을 해제합니다.

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(disposing: 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();
      }
   }
}
open Microsoft.Win32.SafeHandles
open System
open System.ComponentModel
open System.IO
open System.Runtime.InteropServices

// Windows API constants.
let HKEY_CLASSES_ROOT = 0x80000000
let ERROR_SUCCESS = 0
let KEY_QUERY_VALUE = 1
let KEY_SET_VALUE = 0x2
let REG_SZ = 1u
let MAX_PATH = 260

// Windows API calls.
[<DllImport("advapi32.dll", CharSet= CharSet.Auto, SetLastError=true)>]
extern int RegOpenKeyEx(nativeint hKey, string lpSubKey, int ulOptions, int samDesired, nativeint& phkResult)
[<DllImport("advapi32.dll", CharSet= CharSet.Unicode, EntryPoint = "RegQueryValueExW", SetLastError=true)>]
extern int RegQueryValueEx(nativeint hKey, string lpValueName, int lpReserved, uint& lpType, string lpData, uint& lpcbData)
[<DllImport("advapi32.dll", SetLastError = true)>]
extern int RegSetValueEx(nativeint hKey, [<MarshalAs(UnmanagedType.LPStr)>] string lpValueName, int Reserved, uint dwType, [<MarshalAs(UnmanagedType.LPStr)>] string lpData, int cpData)
[<DllImport("advapi32.dll", SetLastError=true)>]
extern int RegCloseKey(unativeint hKey)

type FileAssociationInfo(fileExtension: string) =
    // Private values.
    let ext =
        if fileExtension.StartsWith "." |> not then
            "." + fileExtension
        else
            fileExtension
    let mutable args = ""
    let mutable hAppIdHandle = Unchecked.defaultof<SafeRegistryHandle>
    let mutable hExtHandle = Unchecked.defaultof<SafeRegistryHandle>
    let openCmd = 
        let mutable lpType = 0u
        let mutable hExtension = 0n
        // Get the file extension value.
        let retVal = RegOpenKeyEx(nativeint HKEY_CLASSES_ROOT, fileExtension, 0, KEY_QUERY_VALUE, &hExtension)
        if retVal <> ERROR_SUCCESS then
            raise (Win32Exception retVal)
        // Instantiate the first SafeRegistryHandle.
        hExtHandle <- new SafeRegistryHandle(hExtension, true)

        let appId = String(' ', MAX_PATH)
        let mutable appIdLength = uint appId.Length
        let retVal = RegQueryValueEx(hExtHandle.DangerousGetHandle(), String.Empty, 0, &lpType, appId, &appIdLength)
        if retVal <> ERROR_SUCCESS then
            raise (Win32Exception retVal)
        // We no longer need the hExtension handle.
        hExtHandle.Dispose()

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

        // Open the application identifier key.
        let exeName = String(' ', MAX_PATH)
        let exeNameLength = uint exeName.Length
        let mutable hAppId = 0n
        let retVal = RegOpenKeyEx(nativeint HKEY_CLASSES_ROOT, appId, 0, KEY_QUERY_VALUE ||| KEY_SET_VALUE, &hAppId)
        if retVal <> ERROR_SUCCESS then
            raise (Win32Exception retVal)

        // Instantiate the second SafeRegistryHandle.
        hAppIdHandle <- new SafeRegistryHandle(hAppId, true)

        // Get the executable name for this file type.
        let exePath = String(' ', MAX_PATH)
        let mutable exePathLength = uint exePath.Length
        let retVal = RegQueryValueEx(hAppIdHandle.DangerousGetHandle(), String.Empty, 0, &lpType, exePath, &exePathLength)
        if retVal <> ERROR_SUCCESS then
            raise (Win32Exception retVal)

        // Determine the number of characters without the terminating null.
        let exePath = 
            exePath.Substring(0, int exePathLength / 2 - 1)
            // Remove any environment strings.
            |> Environment.ExpandEnvironmentVariables

        let position = exePath.IndexOf '%'
        if position >= 0 then
            args <- exePath.Substring position
            // Remove command line parameters ('%0', etc.).
            exePath.Substring(0, position).Trim()
        else
            exePath

    member _.Extension =
        ext

    member _.Open
        with get () = openCmd
        and set (value) =
            if hAppIdHandle.IsInvalid || hAppIdHandle.IsClosed then
                raise (InvalidOperationException "Cannot write to registry key.")
            if not (File.Exists value) then
                raise (FileNotFoundException $"'{value}' does not exist")
            
            let cmd = value + " %1"
            let retVal = RegSetValueEx(hAppIdHandle.DangerousGetHandle(), String.Empty, 0, REG_SZ, value, value.Length + 1)
            if retVal <> ERROR_SUCCESS then
                raise (Win32Exception retVal)

    member this.Dispose() =
        this.Dispose true
        GC.SuppressFinalize this

    member _.Dispose(disposing) =
        // Ordinarily, we release unmanaged resources here
        // but all are wrapped by safe handles.

        // Release disposable objects.
        if disposing then
           if hExtHandle <> null then hExtHandle.Dispose()
           if hAppIdHandle <> null then hAppIdHandle.Dispose()

    interface IDisposable with
        member this.Dispose() =
            this.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(disposing:=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