views:

75

answers:

3

There's a few questions on stack overflow on this topic but I'm still unclear:

I know the flash engine is single threaded so when it receives an event, does it essentially break off, execute any registered event listeners (in no guaranteed order) then return to the current scope?

If I have this code:

addListener("stuff", function():void {
     // some stuff
});
addListener("stuff", someFunc);
dispatch(new Event("stuff"));
trace("Done.");

I want to know:

Can I guarantee that both listeners have executed by the time I reach the trace("Done"); line?

edit:

or

can I guarantee that the current function will complete before any of the event listeners execute? ie trace("Done"); will ALWAYS execute first.

or

Neither.

+2  A: 

From what I know, when you dispatch an event it gets added to the event queue, but won't actually run until the currently-executing event finishes. In other words, you'll trace "Done.", then your function ends, control passes back to the event handler, and only then does it (maybe) start executing one of your events.

Anon.
This is how I originally thought it worked. Check my updated question.
secoif
So apparently your model only works that way with external events. Since my function is dispatching the events itself, the listeners are always executed straight away. "If some external event is fired ... then I do not believe that event will be processed until the current routine completes. If foo() itself fires an event, then flow proceeds exactly as you describe it - the event is handled immediately on the single (main) thread. " - http://stackoverflow.com/questions/1267685/does-dispatching-an-event-interrupt-a-function
secoif
+1  A: 

Yes, you can guarantee both assertions in this exact situation. Meaning, that if adding your event listeners and dispatching your event is in the same code block it will happen in sequence. However, from a practical POV that's completely useless.

@kryoko: player events get precedence over user events, but they do not 'force' themselves through. Meaning that if user code is running, the player event handling is suspended. That's why it's possible to 'freeze' a flash movie with heavy, intensive code. (Or with a simple infinite loop, of course)

Creynders
+3  A: 

It is guaranteed that both event handlers will be called before trace because user code generated events are synchronous:
http://stackoverflow.com/questions/1267685/does-dispatching-an-event-interrupt-a-function

James Ward