我如何获得这种情况发生在定时器事件经过的异常? [英] How do I get the Exception that happens in Timer Elapsed event?

查看:155
本文介绍了我如何获得这种情况发生在定时器事件经过的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Windows时窗体应用程序和哈瓦使用System.Timers.Timer到periodly从数据库中查询数据的管理器类。



我如何获得发生在输送到主应用程序定时器经过的事件处理程序的异常?如果我使用下面的代码,异常得到的吞噬,并且主要应用从来没有得到它(即使我有ThreadException和UnHandledException处理程序)。

  //主窗体
Application.ThreadException + =新System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
AppDomain.CurrentDomain.UnhandledException + =新UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

// Manager类
私人System.Timers.Timer _timer;

无效_timer_Elapsed(对象发件人,ElapsedEventArgs E)
{

{
doSomeDatabaseActions();
}
赶上(异常前)
{
抛出新ApplicationException的(我如何得到这个错误返回到主线程......,前);
}
}


解决方案

如果你没有进入主线程,可以抛出另一个异常,非定时器螺纹:

 赶上(例外的例外)
{
ThreadPool.QueueUserWorkItem(
_ => {抛出新的异常(关于计时器例外。除外);});
}


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

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); });
}

这篇关于我如何获得这种情况发生在定时器事件经过的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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