我尝试注册默认事件处理程序,当没有注册其他事件处理程序时,该处理程序被调用(或至少执行)。
特别是我试图在WPF应用程序中为AppDomain.CurrentDomain.UnhandledException
事件注册回退事件处理程序。
问题在于我无法确定事件处理程序是否仍然已注册。因此,这个概念是注册"后备"处理程序。
首先想到的是查看“调用”列表,但为此我必须覆盖AppDomain类并且那令人讨厌。
第二个想法是使用回退处理程序的概念扩展AppDomain类。
private static event UnhandledExceptionEventHandler DomainUnhandledException;
private static event UnhandledExceptionEventHandler DomainFallbackQueue;
private static bool _registeredAppDomainExceptionHandler;
public static void AddUnhandledExceptionFallbackEventHandler(this AppDomain appDomain,
UnhandledExceptionEventHandler handler)
{
if (!_registeredAppDomainExceptionHandler)
{
//we need to register our proxy first
appDomain.UnhandledException += CurrentDomainOnUnhandledException;
_registeredAppDomainExceptionHandler = true;
}
DomainFallbackQueue += handler;
}
public static void AddUnhandledExceptionEventHandler(this AppDomain appDomain,
UnhandledExceptionEventHandler handler)
{
if (!_registeredAppDomainExceptionHandler)
{
//we need to register our proxy first
appDomain.UnhandledException += CurrentDomainOnUnhandledException;
_registeredAppDomainExceptionHandler = true;
}
DomainUnhandledException += handler;
}
private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (DomainUnhandledException?.GetInvocationList().Length == 0 || DomainUnhandledException == null)
{
DomainFallbackQueue?.Invoke(sender, e);
}
else
{
DomainUnhandledException?.Invoke(sender, e);
}
}
通过这种方法,我在App.xaml.cs中注册了回退。
所以我看到的缺点是用户(我们在模块化应用程序中,其他部门开发自己的模块)仍然看到原始appDomain.UnhandledException
,也许不知道使用扩展{ {1}}注册方法。
其次,用户可以通过此方法注册,但未在原始事件上注册AddUnhandledExceptionEventHandler()
运算符。
哦,用户需要在扩展程序中包含名称空间...
那你怎么解决这个问题呢?也许有更好的方法来获得后备处理程序?