Dealing with Asynchronous APIs

A not uncommon complaint when developing for AIR is that asynchronous APIs–especially the filesystem and database APIs–are difficult to use. Why didn’t we make all of these APIs synchronous? So you can write better applications.

In AIR, all ActionScript execution runs on the same thread that updates the display. If your code gets stuck for a long time doing something–like reading a file–then the display won’t get redrawn until your code is done. Your application becomes unresponsive, which users hate.

To avoid this, use the async APIs. They schedule work on background threads and then notify you when it’s done. They don’t block the main thread, thus allowing your app to keep responding even while the work is being done. You’ll get notified when the background work is done via an event.

Does this mean using the async APIs is easy? Absolutely not. In some cases, such as the filesystem API, we offer synchronous alternatives. These are a perfectly good choice if you’re confident that the amount of work you need to do is small and won’t take long. But beware that this isn’t as easy to determine as it might seem: even reading a small file can take a while if it happens to be read from a slow network drive.

You can’t avoid using the async APIs forever, so I recommend also learning some techniques that make them easier to use. In upcoming posts I’ll describe various techniques for accomplishing this, discuss their trade-offs, and share some code that I use to manage asynchronous operation with the runtime itself.

Comments are closed.