在 class 中有两个 System.Timer.Timer 对象并捕获异常

Having two System.Timer.Timer objects in your class and catching exceptions

我有一个 class 和两个 System.Timers.Timer 对象。我现在看到的是,一个抛出的异常被另一个捕获了。这是正确的行为吗?

class MyClass {
    System.Timers.Timer tOne;
    System.Timers.Timer tTwo;

    tOne.Elapsed += new System.Timers.ElapsedEventHandler(one);
    tTwo.Elapsed += new System.Timers.ElapsedEventHandler(two);

    void one(object sender, System.Timers.ElapsedEventArgs e) {
        try {
             .. some code that throws ...
        } catch (Exception) {
               // not caught here
        }
    }

    void two(object sender, System.Timers.ElapsedEventArgs e) {
        try {
        } catch (Exception) {
               // but caught here
        }
    }
}

不同的定时器,异常被抛出异常后ticks的第一个定时器捕获。你的问题主要是因为你用的是单 线程。

System.Timers.Timer 会默默地吞下异常并继续计时(尽管这在框架的未来版本中可能会发生变化); System.Threading.Timer 将终止程序。