在定时器的回调方法中抛出异常 [英] Throwing exceptions in callback method for Timers

查看:22
本文介绍了在定时器的回调方法中抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在任何地方找到这个问题的答案...

I was unable to find an answer to this question anywhere...

在 System.Threading.Timer 的回调方法(或 System.Timers.Timer 的事件处理程序)中抛出的异常会发生什么.异常是传播到创建计时器的线程还是异常丢失了?

What happens with the exceptions thrown in the callback method for System.Threading.Timer, (or in the event handler for System.Timers.Timer). Is the exception propagated to the thread on which the timer was created or is the exception lost?

在定时器的回调函数中抛出异常有什么副作用?

What are the side-effects of throwing an exception within the timer's callback functions?

向计时器的创建线程通知工作线程(回调方法)中的异常已被抛出的正确方法是什么?

What would be the right way to signalize to the timer's creation thread that the exception in the worker thread (callback method) has been thrown?

感谢您的时间.

推荐答案

异常不会传递回调用线程.如果您愿意,可以添加一个 catch 块并找出一种方法来向调用线程发送信号.如果调用线程是 WinForms 或 WPF UI 线程,则可以使用 SynchronizationContext 类将调用传递给 UI 线程.否则,您可以使用线程安全队列(或同步锁)并在另一个线程中定期检查它.

The exception is not passed back to the calling thread. If you want it to be, you can add a catch block and figure out a way to signal the calling thread. If the calling thread is a WinForms or WPF UI thread, you can use the SynchronizationContext class to pass a call to the UI thread. Otherwise, you could use a thread-safe queue (or a sync lock) and check it periodically in the other thread.

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

System.Timers.Timer will silently swallow exceptions and continue the timer (although this is subject to change in future versions of the framework); System.Threading.Timer will terminate the program.

这篇关于在定时器的回调方法中抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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