# How do I call functions that take more than one frame to finish?

I'm trying to figure out how to implement C# scripting into my XNA game. How do I call functions that take more than one frame to finish?

For example:

class UserScript : Script
{
public override void execute(Game game)
{
//script must wait for dialog to be closed
game.openDialog("This is a dialog");

//script should'nt wait for this
int goldToGive = 100;
goldToGive += 100;
//

//script should wait for cinematic to end
game.startCinematic("name_of_cinematic");

//doesn't wait
}
}


I found a question that suggests you can do it with yield, but I'm not sure if it's the correct way, as the referenced article is from 2010, and no longer exists. Is using yield the answer? If so, how do I use it? If not, should I take a differant approach, or am I better off with multi-threading?

• in new c# there is compiler as service, that you could use to interpret just some code instead of all, or you can use some IL interpreter (i think mono has one inside), or use yield (thats what unity does) or run each script as separate task (thread) – Kikaimaru Dec 8 '12 at 21:41

You can find the mentioned article in the internet archive: The magic of yield.
As mentioned in the conclusion of the article, you don't have to return a "float", but rather a custom type that you can query for all sorts of results.
In the case of your dialog (and in the same way for your cinematic), you can write something like:

Dialog dialog = game.openDialog("This is a dialog");
while (dialog.isOpen) {
yield return 1f;
}
//Continue script...


Since yield is just generating a state machine for you, you can just as easily roll your own and implement a bunch of tasks to be executed in some sort of collection. Or use yield and use the results for something (time to wait, state to be in, etc.). Good discussion about all this with some images can be found here: https://stackoverflow.com/questions/5923767/simple-state-machine-example-in-c

Consider using reflection instead. You can provide dlls with classes to call and types/interfaces to uYpse. Users can compile code and drop dlls in a particular folder for you to load at runtime. Same for content.