我的C#代码使用模拟由通过P调用Win32函数/调用为什么来自模拟代码的异常未被捕获?
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;
}
还我AppDomain.CurrentDomain.UnhandledException
处理程序安装还记录所有未处理的异常。
我敢肯定,记录异常的代码在使用和不使用模拟时都可以正常工作。
现在的问题是,在上面的代码中,它看起来像没有输入catch
,UnhandledException
也没有被调用。事件查看器中的条目是唯一的异常跟踪。
如果我添加一个finally
这样的:
try {
var token = obtainTokenFromLogonUser();
Win32Native.ImpersonateLoggedOnUser(token);
try {
throw new Exception(); // this is for simulation
} finally {
Win32Native.RevertToSelf()
}
} catch(Exception e) {
LogException(e);
throw;
}
则异常无论从catch
和UnhandledException
处理记录好。
发生了什么事?被模拟的线程是否阻止了常规的异常处理?
如果你在'LogException'上放置一个断点:你到那里了吗? – 2013-03-15 10:02:18
@MarcGravell:我不知道,没有调试器在哪里复制。我意识到'LogException()'本身可能存在一些问题,但到目前为止,它所依赖的代码都可以正常工作,并且不会被模拟。 – sharptooth 2013-03-15 10:04:12
在这里做一个猜测:因为.NET会跟踪执行上下文,所以异常处理可能会意识到上下文已经改变,并且正在阻止异常处理程序执行,除非首先执行回复。如果代码与模拟用户一起运行,则不这样做会导致特权提升...... – 2013-03-15 12:26:11