System.Object.Finalize, metoda

Ten artykuł zawiera dodatkowe uwagi dotyczące dokumentacji referencyjnej dla tego interfejsu API.

Metoda Finalize służy do wykonywania operacji oczyszczania na niezarządzanych zasobach przechowywanych przez bieżący obiekt przed zniszczeniem obiektu. Metoda jest chroniona i dlatego jest dostępna tylko za pośrednictwem tej klasy lub za pośrednictwem klasy pochodnej.

Jak działa finalizacja

Klasa Object nie zapewnia implementacji dla Finalize metody, a moduł odśmiecania pamięci nie oznacza typów pochodnych Object na potrzeby finalizacji, chyba że zastąpią metodę Finalize .

Jeśli typ zastępuje Finalize metodę, moduł odśmiecania pamięci dodaje wpis dla każdego wystąpienia typu do wewnętrznej struktury nazywanej kolejką finalizacji. Kolejka finalizacji zawiera wpisy dla wszystkich obiektów w zarządzanym stercie, którego kod finalizacji musi zostać uruchomiony, zanim moduł odśmiecania pamięci może odzyskać pamięć. Moduł odśmiecający elementy bezużyteczne wywołuje metodę Finalize automatycznie w następujących warunkach:

  • Gdy moduł odśmiecania pamięci wykrył, że obiekt jest niedostępny, chyba że obiekt został wykluczony z finalizacji przez wywołanie GC.SuppressFinalize metody .
  • Tylko w programie .NET Framework podczas zamykania domeny aplikacji, chyba że obiekt jest wykluczony z finalizacji. Podczas zamykania nawet obiekty, które są nadal dostępne, są finalizowane.

Finalize jest wywoływany automatycznie tylko raz w danym wystąpieniu, chyba że obiekt zostanie ponownie zarejestrowany przy użyciu mechanizmu takiego jak GC.ReRegisterForFinalize i GC.SuppressFinalize metoda nie została następnie wywołana.

Finalize operacje mają następujące ograniczenia:

  • Dokładny czas wykonania finalizatora jest niezdefiniowany. Aby zapewnić deterministyczne wydanie zasobów dla wystąpień klasy, zaimplementuj metodę Close lub podaj implementację IDisposable.Dispose .
  • Finalizatory dwóch obiektów nie są gwarantowane do uruchomienia w określonej kolejności, nawet jeśli jeden obiekt odwołuje się do drugiego. Oznacza to, że jeśli obiekt A ma odwołanie do obiektu B i oba mają finalizatory, obiekt B mógł już zostać sfinalizowany po uruchomieniu finalizatora obiektu A.
  • Wątek, na którym działa finalizator, jest nieokreślony.

Metoda Finalize może nie zostać uruchomiona do ukończenia lub w ogóle nie działać w następujących wyjątkowych okolicznościach:

  • Jeśli inny finalizator blokuje się na czas nieokreślony (przechodzi do nieskończonej pętli, próbuje uzyskać blokadę, która nigdy nie może uzyskać itd.). Ponieważ środowisko uruchomieniowe próbuje uruchomić finalizatory do ukończenia, inne finalizatory mogą nie być wywoływane, jeśli finalizator blokuje się na czas nieokreślony.
  • Jeśli proces zakończy się bez możliwości wyczyszczenia środowiska uruchomieniowego. W takim przypadku pierwsze powiadomienie środowiska uruchomieniowego o zakończeniu procesu jest powiadomieniem DLL_PROCESS_DETACH.

Środowisko uruchomieniowe nadal finalizuje obiekty podczas zamykania tylko wtedy, gdy liczba finalizowalnych obiektów nadal spada.

Jeśli Finalize lub zastąpienie Finalize zgłasza wyjątek, a środowisko uruchomieniowe nie jest hostowane przez aplikację, która zastępuje zasady domyślne, środowisko uruchomieniowe przerywa proces i nie są wykonywane żadne aktywne try/finally bloki lub finalizatory. To zachowanie zapewnia integralność procesu, jeśli finalizator nie może zwolnić lub zniszczyć zasobów.

Zastępowanie metody Finalize

Należy zastąpić Finalize klasę, która używa niezarządzanych zasobów, takich jak dojście do plików lub połączenia bazy danych, które muszą zostać zwolnione, gdy zarządzany obiekt, który z nich korzysta, zostanie odrzucony podczas odzyskiwania pamięci. Nie należy implementować Finalize metody dla obiektów zarządzanych, ponieważ moduł odśmiecający śmieci automatycznie zwalnia zarządzane zasoby.

Ważne

SafeHandle Jeśli obiekt jest dostępny, który opakowuje niezarządzany zasób, zalecaną alternatywą jest zaimplementowanie wzorca usuwania przy użyciu bezpiecznego uchwytu i nie przesłaniania Finalizeelementu . Aby uzyskać więcej informacji, zobacz sekcję alternatywną Sejf Handle.

Metoda Object.Finalize nie wykonuje nic domyślnie, ale należy zastąpić Finalize tylko w razie potrzeby i tylko do zwolnienia niezarządzanych zasobów. Odzyskiwanie pamięci zwykle trwa znacznie dłużej, jeśli operacja finalizacji zostanie uruchomiona, ponieważ wymaga co najmniej dwóch odzyskiwania pamięci. Ponadto należy zastąpić metodę Finalize tylko dla typów odwołań. Środowisko uruchomieniowe języka wspólnego finalizuje tylko typy odwołań. Ignoruje finalizatory typów wartości.

Zakres Object.Finalize metody to protected. Należy zachować ten ograniczony zakres podczas zastąpienia metody w klasie. Dzięki zachowaniu Finalize ochrony metody uniemożliwia użytkownikom aplikacji bezpośrednie wywoływanie metody obiektu Finalize .

Każda implementacja Finalize klasy w typie pochodnym musi wywoływać implementację typu podstawowego Finalize. Jest to jedyny przypadek, w którym kod aplikacji może wywołać metodę Finalize. Metoda obiektu Finalize nie powinna wywoływać metody na żadnych obiektach innych niż metoda podstawowa. Jest tak, ponieważ inne wywołania obiektów mogą być kolekcjonowane w tym samym czasie, co obiekt wywołujący, tak jak w przypadku zamknięcia środowiska uruchomieniowego języka wspólnego.

Uwaga

Kompilator języka C# nie umożliwia zastąpienia Finalize metody . Zamiast tego należy podać finalizator, implementując destruktor dla klasy. Destruktor języka C# automatycznie wywołuje destruktor klasy bazowej.

Język Visual C++ udostępnia również własną składnię Finalize do implementowania metody. Aby uzyskać więcej informacji, zobacz sekcję "Destruktory i finalizatory" w temacie How to: Define and Consume Classes and Structs (C++/CLI)( Definiowanie i używanie klas i struktur (C++/CLI).

Ponieważ odzyskiwanie pamięci nie jest deterministyczne, nie wiadomo dokładnie, kiedy moduł odśmiecania pamięci wykonuje finalizację. Aby natychmiast zwolnić zasoby, możesz również wdrożyć wzorzec usuwania i IDisposable interfejs. Implementacja IDisposable.Dispose może być wywoływana przez odbiorców klasy, aby zwolnić niezarządzane zasoby i można użyć Finalize metody , aby zwolnić niezarządzane zasoby w przypadku, gdy Dispose metoda nie jest wywoływana.

Finalize może wykonać niemal dowolną akcję, w tym wskrzesić obiekt (czyli ponownie udostępnić obiekt) po wyczyszczeniu go podczas odzyskiwania pamięci. Jednak obiekt można wskrzesić tylko raz; Finalize nie można wywołać wskrzeszania obiektów podczas odzyskiwania pamięci.

Alternatywa Sejf Handle

Tworzenie niezawodnych finalizatorów jest często trudne, ponieważ nie można założyć założeń dotyczących stanu aplikacji i dlatego, że nieobsługiwane wyjątki systemowe, takie jak OutOfMemoryException i StackOverflowException zakończą finalizator. Zamiast implementować finalizator klasy w celu zwolnienia niezarządzanych zasobów, można użyć obiektu pochodzącego z System.Runtime.InteropServices.SafeHandle klasy, aby opakowować niezarządzane zasoby, a następnie zaimplementować wzorzec usuwania bez finalizatora. Program .NET Framework udostępnia następujące klasy w Microsoft.Win32 przestrzeni nazw, które pochodzą z System.Runtime.InteropServices.SafeHandleprogramu :

W poniższym przykładzie użyto wzorca usuwania z bezpiecznymi uchwytami zamiast zastępowania Finalize metody. Definiuje klasę FileAssociation , która opakowuje informacje rejestru o aplikacji, która obsługuje pliki z określonym rozszerzeniem pliku. Dwa rejestry obsługują zwracane jako out parametry wywołań funkcji RegOpenKeyEx systemu Windows są przekazywane do konstruktoraSafeRegistryHandle. Metoda chroniona Dispose typu wywołuje metodę SafeRegistryHandle.Dispose , aby zwolnić te dwa uchwyty.

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