title: Cryptographic Exception when PKI SmartCard is removed in .NET
body: <p>I am using X509 certificates for authentication. When the SmartCard is removed we sometimes encounter the following Exception (unfortunately I have to exception text only in german...)</p>
  
  <p>"Ungültige Benutzerkennung" which means something like "Invalid user id":</p>
  
  <pre><code>    bei System.Security.Cryptography.CryptographicException.ThrowCryptogaphicException(Int32 hr)
      bei System.Security.Cryptography.SafeKeyHandle._FreeHKey(IntPtr pKeyCtx)
      bei System.Security.Cryptography.SafeKeyHandle.ReleaseHandle()
      bei System.Runtime.InteropServices.SafeHandle.InternalFinalize()
      bei System.Runtime.InteropServices.SafeHandle.Dispose(Boolean disposing)
      bei System.Runtime.InteropServices.SafeHandle.Finalize()
  </code></pre>
  
  <p>I have peeked into the implementation of the X509Certificate. It seems that the Garbage Collector invokes the finalizer of the X509Certificate. The X509Certificate object contains Win32 Handles. Now, when the SmartCard is removed the according certificates are also removed from the windows certificate store, thus the underlying Win32 Handles are probably refering to Win32 ressources which are not around anymore (the certificates in the certificate store).</p>
  
  <p>My problem is that I cannot catch and handle this exception since it is thrown inside the finalizer at some point in the time when the garbage collector kicks in. This exception then tears down the whole application...</p>
  
  <p>I tried to explicitly call X509Certificate2.Reset() but the error still occurs in the finalizer.</p>
  
  <p>Any ideas on how to fix this issue?</p>
  
  <p>Regards,
  Sebastian</p>