如何使用Timer(Thread)类处理异常
我正在尝试处理计时器的异常。如果类有像 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!");
}
}
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: 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!");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为 Timer 类不支持这样的事件,否则您将如何捕获异常?
如果您坚持使用 Timer 类,那么也许这是您唯一的选择:
这样,实际的处理程序 t_Elapsed 不包含任何错误处理,您可以为 Timer 类创建一个包装类来隐藏它实现细节,进而提供异常处理的事件。
这是一种方法:
Since the Timer class doesn't support such an event how would you otherwise catch an exception?
If you insist on using the Timer class then perhaps this is your only option:
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: