Is it possible to have one Exception handler for multiple timers in a C# class?

我只是一个虾纸丫 提交于 2019-12-06 11:45:55
khargoosh

If your timer is a System.Timers.Timer the reason is documented by MSDN here:

The Timer component catches and suppresses all exceptions thrown by event handlers for the Elapsed event.

Take a look at this similar question: How do I get the Exception that happens in Timer Elapsed event?

You'll have to catch the exceptions that are thrown in the elapsed handler, and rethrow them on a ThreadPool thread.

Using your code above and extending the answer from the referenced question:

private void ChangeFilesTimer_Tick(object sender, EventArgs e)
{
    try
    {
        RunChangeFiles();
    }
    catch (Exception ex)
    {
        ThreadPool.QueueUserWorkItem(
            _ => { throw new Exception("Exception on timer thread.", ex); });
    }
}

If your timer is a System.Windows.Forms.Timer then you will need to hook into the Application.ThreadException event to handle unhandled exceptions.

Subscribe to this event prior to calling Application.Run().


You can also handle logging of the Exception in a local exception handling block before rethrowing the exception.

try
{
    /// ...
}
catch (Exception ex)
{
    if (ex is ArgumentException)
    {
        /// handle known or specific exceptions here
    }
    else 
    {
        /// log then rethrow unhandled exceptions here
        logExceptions(ex);
        throw;  
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!