如何使用Timer(Thread)类处理异常 [英] How to handle exception using Timer (Thread) class

查看:99
本文介绍了如何使用Timer(Thread)类处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试处理Timer的异常.如果该类具有类似HandlerExceptionEvent的类,那就太好了,这样我们就可以添加一些事件来记录点什么或停止计时器.

I'm trying to handle the Timer's exception. It would be nice if the class had something like HandlerExceptionEvent so that we could add some event to log something or stop the timer.

PS:我不想在ElapsedEventHandler()内添加try/catch块.

PS: I don't want to add a try/catch block inside ElapsedEventHandler().

class Program
{
static void Main(string[] args) {
  System.Timers.Timer t = new System.Timers.Timer(1000);
  t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
  t.Start();     

  System.Threading.Thread.Sleep(10000);
  t.Stop();
  Console.WriteLine("\nDone.");      
  Console.ReadLine();
}

 static void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
   Console.WriteLine("Ping!");
   throw new Exception("Error!");
 }
}

推荐答案

PS:我不想在ElapsedEventHandler()中添加"try/catch Exception"

PS: I don't want to add "try/catch Exception" inside ElapsedEventHandler()

由于Timer类不支持此类事件,否则您将如何捕获异常?

Since the Timer class doesn't support such an event how would you otherwise catch an exception?

如果您坚持使用Timer类,那么也许这是您唯一的选择:

If you insist on using the Timer class then perhaps this is your only option:

var t = new System.Timers.Timer(1000);
t.Elapsed += (sender, e) => { 
    try 
    { 
        t_Elapsed(sender, e); 
    } 
    catch (Exception ex) 
    { 
        // Error handling here...
    } 
};

这样,实际的处理程序t_Elapsed不包含任何错误处理,您可以为Timer类创建一个包装器类,该包装器类隐藏此实现细节,并依次提供事件以进行异常处理.

This way the actual handler t_Elapsed doesn't contain any error handling and you can create a wrapper class for the Timer class that hides this implementation detail and in turn provides an event for exception handling.

这是做到这一点的一种方法:

Here's one way to do that:

class ExceptionHandlingTimer
{
    public event Action<Exception> Error;

    System.Timers.Timer t;

    public ExceptionHandlingTimer(double interval)
    {
        t = new System.Timers.Timer(interval);
    }

    public void Start()
    {
        t.Start();
    }

    public void AddElapsedEventHandler(ElapsedEventHandler handler)
    {
        t.Elapsed += (sender, e) =>
        {
            try
            {
                handler(sender, e);
            }
            catch (Exception ex)
            {
                if (Error != null)
                {
                    Error(ex);
                }
                else
                {
                    throw;
                }
            }
        };
    }
}

这篇关于如何使用Timer(Thread)类处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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