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.
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:
- Programming User interfaces using F# workflows
As I said, you could simulate this in C# using yield return
. Here is my attempt:
- Asynchronous programming in C# using iterators
Another approach based on yield return
is the Concurrency and coordination runtime, which is a bit more complicated, but was designed primarily for C#.
精彩评论