I have the need to create a queue-based system where multiple threads will add acti开发者_StackOverflowons to be processed by the queue.
Sounds simple enough, but my actions will be asynchronous (with animations) so I do not want to start the next action in the queue until the animation of the previous action is completed.
How could I do this?
You can make an IAction
interface with an Execute
method and a Completed
event.
You can then make a queue of IAction
s and pop and Execute
the next item in the Completed
handler for the current item.
You can even make an iterator method that yield return
s IAction
s and have the queue call MoveNext()
after each IAction
finishes.
EDIT: For example:
class ActionEnumerator : IAction {
readonly IEnumerator<IAction> enumerator;
public ActionEnumerator(IEnumerator<IAction> enumerator) {
this.enumerator = enumerator;
}
public void Execute() {
//If the enumerator gives us another action,
//hook up its Completed event to continue the
//the chain, then execute it.
if (enumerator.MoveNext()) {
enumerator.Current.Completed += delegate { Execute(); };
enumerator.Current.Execute();
} else //If the enumerator didn't give us another action, we're finished.
OnCompleted();
}
}
IEnumerator<IAction> SomeMethod() {
...
yield return new SomeAction();
//This will only run after SomeAction finishes
...
yield return new OtherAction();
...
}
精彩评论