2

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.

4

1 回答 1

0

你的问题不是很清楚。问题是“等待”时你想做什么?例如,如果您谈论的是 WinForms GUI 应用程序,那么您可能希望在等待时处理其他事件(这可以使用该Application.DoEvents方法完成),所以也许您可以使用类似的解决方案?

yield return可以在 C# 中使用 iterators (the ) 关键字模拟轻量级协作多线程(可能类似于 Ruby 纤维) 。在 .NET 中执行此类操作的更好方法是使用 F#,您可以使用异步工作流更优雅地执行此类操作。这是一篇演示如何编写单线程 GUI 的文章,您可以在其中“等待”事件发生而不会阻塞:

正如我所说,您可以在 C# 中使用yield return. 这是我的尝试:

另一种基于并发和协调运行时yield return的方法,它有点复杂,但主要是为 C# 设计的。

于 2010-03-10T02:46:58.060 回答