【问题标题】:How to handle exception using Timer (Thread) class如何使用 Timer (Thread) 类处理异常
【发布时间】:2011-03-23 14:38:59
【问题描述】:

我正在尝试处理Timer 的异常。如果该类有类似HandlerExceptionEvent 这样的东西会很好,这样我们就可以添加一些事件来记录某些内容或停止计时器。

PS:我不想在ElapsedEventHandler() 中添加try/catch 块。

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

【问题讨论】:

  • 为什么不想在事件处理程序中添加try-catch
  • 因为我知道如何尝试/捕获。 :-) 我想知道我是否可以使用我不知道的东西。

标签: c# multithreading timer handler


【解决方案1】:

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

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

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

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 类创建一个包装类,该类隐藏此实现细节,进而为异常处理提供一个事件。

这是一种方法:

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

【讨论】:

  • +1 - 虽然 lambda 可以方便地解决生成您自己的特定回调的范围问题,但经过的回调确实包含错误处理 =D
  • @Tejs 我没有关注...如果您没有 try/catch 块,则无法使用 Timer 类捕获错误。
  • 你知道任何与 X 类似但有 HandlerException 的类吗?
  • @Makah - 好吧,我已经为你提供了一个,为什么不使用我为你写的那个?
  • 这个包装器是个好主意,但我期待 .NET Framework 已经为它准备好了一些东西。
猜你喜欢
  • 2017-05-13
  • 1970-01-01
  • 1970-01-01
  • 2010-10-16
  • 2012-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-09
相关资源
最近更新 更多