等待直到调用代表
我有一个带有 StartProcessing()
方法的异步类,该方法在完成处理时引发 int ResultReady()
事件。 StartProcessing()
只需要很少的时间。
我想同步调用这个类。我的伪代码应该类似于:
Call StartProcessing()
等待/睡眠直到结果准备好
返回结果
哪种设计模式最适合这个?你能指点我一个代码示例吗?
I have an asynchronous class with a StartProcessing()
method, that raises an int ResultReady()
event when it has finished processing. StartProcessing()
takes very little time.
I want to call this class synchronously. My pseudo-code should be something like:
Call StartProcessing()
Wait/sleep until result is ready
Return result
What design pattern is best for this? Can you please point me to a code example?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种简单的方法是使用
ManualResetEvent
。调用
设置
来自事件处理程序,以及WaitOne
(或来自等待线程的超时过载)。请注意,这不能在 STA 线程上完成,因此您不能在 WinForms 线程(应该始终是 STA)内执行此操作 - 但无论如何您都不应该在 UI 线程内等待。像这样的东西:
One simple way of doing this is with a
ManualResetEvent
which the event handler and the waiting code both have access to. CallSet
from the event handler, andWaitOne
(or an overload with a timeout) from the waiting thread. Note that this can't be done on an STA thread, so you can't do it within a WinForms thread (which should always be STA) - but you shouldn't be waiting within a UI thread anyway.Something like this: