紧凑框架:Timer.Dispose 不阻塞

发布于 2024-09-30 09:43:46 字数 501 浏览 0 评论 0原文

更新:计时器是一个System.Threading.Timer。

我们有一个在 Timer Tick 上更新的 UI 控件。在处理我们的控件时,我们调用timer.Dispose()。当调用 UI 控件后触发计时器时,我们偶尔会遇到 ObjectDisposeOException。

我在 msdn 文档 中看到了这一点:

“调用 Dispose() 方法重载后可能会发生回调,因为计时器将回调排队以供线程池线程执行。您可以使用 Dispose(WaitHandle) 方法重载来等待,直到所有回调完成。”

但是,Compact Framework 无法访问该重载方法。

对于这种情况,最好的解决方法是什么?有没有办法让我们的 Dispose 方法阻塞,直到计时器完全释放为止?其他建议?

谢谢你!

UPDATE: The Timer is a System.Threading.Timer.

We have a UI control that is updated on Timer Tick. On dispose of our control we call timer.Dispose(). We are running into occasional ObjectDisposedOExceptions when the timer fires after the UI control has been invoked.

I see this in the msdn docs:

"Callbacks can occur after the Dispose() method overload has been called, because the timer queues callbacks for execution by thread pool threads. You can use the Dispose(WaitHandle) method overload to wait until all callbacks have completed."

However, the Compact Framework does NOT have access to that overloaded method.

What is the best workaround for this situation? Is there a way to make our Dispose method block until the timer has been fully disposed? Other suggestions?

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

执手闯天涯 2024-10-07 09:43:46

我不确定阻止 Dispose 是否是一个好主意。有很多事情可能会出错,导致事情处于不干净的状态。

我会检查计时器回调上的控件是否为空。或者,您可以将计时器回调放在 try 块内并捕获 ObjectDisposeException,但这将消耗更多资源(异常抛出/捕获非常昂贵。)

这应该只发生在线程池中的线程耗尽之前,听起来像如果计时器发出几次信号但由于控件为空而没有执行任何操作,则没有真正的问题。

I'm not sure it would be a good idea to block on Dispose. There are a number of things that could go wrong that could leave things in an unclean state.

I would instead check for the control being null on your timer callback. Alternatively you could put your timer callback inside of a try block and catch the ObjectDisposedException but this will consume a lot more resources (exception throwing/catching is very expensive.)

This should only happen until the threads in the threadpool are exhausted and it sounds like there's no real problem if the timer signals a couple times but doesn't do any work because the control is null.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文