My C# code uses impersonation by calling Win32 functions via P/Invoke
internal class Win32Native
{
[DllImport("advapi32.dll", SetLastError = true)]
public static extern int ImpersonateLoggedOnUser(IntPtr token);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern int RevertToSelf();
}
try {
var token = obtainTokenFromLogonUser();
Win32Native.ImpersonateLoggedOnUser( token );
throw new Exception(); // this is for simulation
Win32Native.RevertToSelf()
} catch( Exception e ) {
LogException( e );
throw;
}
also I have AppDomain.CurrentDomain.UnhandledException
handler installed that also logs all unhandled exception.
I'm sure that the code that logs exceptions works fine both with and without impersonation.
Now the problem is that in the above code it looks like catch
is not entered and UnhandledException
is also not called. The only trace of the exception is an entry in the Event Viewer.
If I add a finally
like this:
try {
var token = obtainTokenFromLogonUser();
Win32Native.ImpersonateLoggedOnUser( token );
try {
throw new Exception(); // this is for simulation
} finally {
Win32Native.RevertToSelf()
}
} catch( Exception e ) {
LogException( e );
throw;
}
then the exception is logged okay both from catch
and from UnhandledException
handler.
What's happening? Does the thread being impersonated prevent usual exception handling?