如何获得 Timer Elapsed 事件中发生的异常? [英] How do I get the Exception that happens in Timer Elapsed event?

查看:18
本文介绍了如何获得 Timer Elapsed 事件中发生的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Windows 窗体应用程序,并使用 System.Timers.Timer 定期检查数据库中的数据的管理器类.

I'm working with Windows Forms application and hava a manager class that uses System.Timers.Timer to periodly check data from database.

如何获取传递到主应用程序的计时器 Elapsed 事件处理程序中发生的异常?如果我使用下面的代码,异常会被吞下",而主应用程序永远不会得到它(即使我有 ThreadException 和 UnHandledException 的处理程序).

How do I get the Exception that occurs in timer Elapsed eventhandler delivered into main application? If I'm using the code below, the exception get's "swallowed", and main application never gets it (even if I have handlers for ThreadException and UnHandledException).

// Main Form
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

// Manager class
private System.Timers.Timer _timer;

    void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        try
        {
            doSomeDatabaseActions();
        }
        catch (Exception ex)
        {
            throw new ApplicationException("How do I get this error back into main thread...", ex);
        }
    }

推荐答案

如果您无权访问主线程,则可以在另一个非定时器线程上抛出异常:

If you don't have access to the main thread, you can throw the exception on another, non-timer thread:

catch (Exception exception)
{
    ThreadPool.QueueUserWorkItem(
        _ => { throw new Exception("Exception on timer.", exception); });
}

这篇关于如何获得 Timer Elapsed 事件中发生的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆