I have a System.Timers.Timer
object, and within its Elapsed method I want to call myObject.TriggerEvent(...)
, but I want that invocation to happen on the thread myObject
was created on. Is there an easy way to do this? And is this a bad idea for any reason? myObject
is basically an event manager service, so I want it to trigger events on the thread it was created on. The reason I'm using the timer is because I have another that is polling a service for updates, which it notifies myObject
of via the TriggerEvent
method.
问问题
154 次
2 回答
1
您可以制作自己的SynchronizationContext实现并将其实例提供给myObject.TriggerEvent
. 如果您myObject
在 WPF、SL 或 WinForms 应用程序中使用,您可以使用它们现有的 SynchronizationContext 类实现并myObject
在 GUI 线程上创建。
于 2012-07-03T19:13:34.597 回答
0
我建议使用Dispatcher。它是在 WPF 的上下文中创建的,但没有理由不能在其他地方使用它。我已经用过几次了,但我总是有一个消息泵(Win32),但我相信它也可以在服务上下文中使用(IIS 等)——但是我还没有写过这样的代码,所以YMMV。这是一篇从 WPF 角度看的好文章。
埃里克
于 2012-07-03T20:05:20.853 回答