在单线程 API 中处理事件处理程序休眠的最佳方法是什么?
我正在使用非线程安全事件 API。 wait()
被调用,并从该调用中调度事件处理程序。我希望能够在事件处理程序中“休眠”一段时间。目前,我有一个调度程序,可以安排稍后调用的函数,并且有一些技巧可以让我使用 Scheduler.Sleeper(some_ienumerator) 作为事件处理程序,这样我就可以将时间跨度作为一种睡眠。还有更好的解决办法吗?如果 C# 有 Ruby 风格的 Fibers,我将能够让调度程序有一个可以调用的 Sleep() 函数,并且睡眠内容可以在事件处理程序调用的函数中,而不是直接在处理程序中。鉴于缺乏易于使用的纤维,我还能做些什么吗?
编辑以澄清:我调用 wait(n)
,其中 n 是时间量,在该等待调用期间,API 调用事件处理程序。我想在其中一些处理程序中“睡眠”的原因是因为这是一个游戏,在点击某物后,一个对象可能会发光一秒钟。
I'm using a non-threadsafe event API. wait()
is called, and from that call, event handlers are dispatched. I want to be able to, within an event handler, "sleep" for some time. Currently, I have a scheduler that schedules functions to be called at a later time, and have a bit of a hack that lets me use Scheduler.Sleeper(some_ienumerator) as the event handler, so I can yield timespans as a sort of sleep. Is there any better solution? If C# had Ruby-style Fibers, I would be able to make the scheduler have a Sleep() function that I can call, and the sleep stuff could be in a function called by the event handler, rather than the handler directly. Given the lack of easily-usable Fibers, is there anything else I can do?
EDIT FOR CLARIFICATION: I call wait(n)
where n is an amount of time, and during that wait call, the API calls the event handlers. The reason I want to "sleep" in some of those handlers is because this is for a game, where after clicking on something, an object might, for instance, glow for a second.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的问题不是很清楚。问题是“等待”的时候你想做什么?例如,如果您正在谈论 WinForms GUI 应用程序,那么您可能希望在等待时处理其他事件(这可以使用
Application.DoEvents
方法完成),所以也许您可以使用类似的解决方案?可以使用迭代器(
yield return
)关键字在 C# 中模拟轻量级协作多线程(可能类似于 Ruby 纤维)。在 .NET 中执行此类操作的更好方法是使用 F#,您可以使用异步工作流程更优雅地执行此类操作。这里有一篇文章演示了编写单线程 GUI,您可以在其中“等待”事件发生而不会阻塞:正如我所说,您可以使用
yield return
在 C# 中模拟这一点。这是我的尝试:另一种基于
的方法Yield return
是并发和协调运行时,有点复杂,但主要是为 C# 设计的。Your question isn't very clear. The question is what do you want to do while "waiting"? If you were talking for example about WinForms GUI applications, then you would want to process other events while waiting (which can be done using the
Application.DoEvents
method), so maybe you could use a similar solution?A lightweight cooperative multi-threading (probably similar to Ruby fibers) can be simulated in C# using iterators (the
yield return
) keyword. Much better way to do something like this in .NET is to use F#, where you can do this kind of things more elegantly using asynchronous workflows. Here is an article that demonstrates writing single-threaded GUI where you can "wait" for an event occurrence without blocking:As I said, you could simulate this in C# using
yield return
. Here is my attempt:Another approach based on
yield return
is the Concurrency and coordination runtime, which is a bit more complicated, but was designed primarily for C#.