我正在将一些 .NET 5 代码迁移到 .NET Standard 2.1 以供更广泛的使用,但
Marshal.GetExceptionPointers()
方法尚未标准化。
是否有其他方法可以检测 .NET Standard 2.1 中的异常上下文?
当前代码
public static bool IsInExceptionContext()
=> Marshal.GetExceptionPointers() != IntPtr.Zero || Marshal.GetExceptionCode() != 0;
您可以简单地使用反射:
public static class ExceptionHelper
{
private static readonly MethodInfo GetExceptionPointersMethod = typeof(Marshal).GetMethod("GetExceptionPointers");
public static bool IsInExceptionContext()
{
var ptr = (IntPtr)GetExceptionPointersMethod.Invoke(null, null);
if (ptr == IntPtr.Zero)
{
return false;
}
return true;
}
}
如果您想避免反射(出于性能原因),您可以动态构建一个将调用
LambdaExpression
方法的 Marshal.GetExceptionPointers()
。
internal static class ExceptionHelper
{
private static readonly Func<IntPtr> GetExceptionPointers = BuildGetExceptionPointersFunc();
public static bool IsInExceptionContext()
{
var ptr = GetExceptionPointers();
if (ptr == IntPtr.Zero)
{
return false;
}
return true;
}
private static Func<IntPtr> BuildGetExceptionPointersFunc()
{
var memberAccess = Expression.Call(typeof(Marshal).GetMethod("GetExceptionPointers"));
var lambda = Expression.Lambda<Func<IntPtr>>(memberAccess);
return lambda.Compile();
}
}