Products
Technologies

Developer resources

Is multi-threading possible in Flash or ActionScript?

Avg. Rating 3.3

Problem

Executing ActionScript code that takes a lot of time may potentially block the UI from being re-drawn. Is it possible to have threading in AS3 so that your task can be executed in the background without blocking the UI from being re-drawn?

Solution

There's no built-in way to do threading in ActionScript. You have to write code to fake it so that you have the equivalent of a pseudo-thread.

Detailed explanation

Write a function that performs one iteration of whatever operation you want to do. It should return true or false depending on if its job is done or not. Now, you have to compute the time interval left to the next screen update on the ENTER_FRAME event. This can be done using flash.utils.getTimer.

start = getTimer();
//thread is a ui component added to system manager that is redrawn each frame
var fr:Number = Math.floor(1000 / thread.systemManager.stage.frameRate);
due = start + fr;

Keep on executing your function while checking the function's return value each time and checking if due time has been crossed by comparing getTimer() with due. The idea is that you execute your long task in chunks before the time for the next screen update is up.

This has been implemented into a usable class by Alex Harui in the blog entry - Threads in ActionScript

 

Update: As the commenter ardnarf1 points out, flash player 10 supports pixel bender kernels (programs) that can run as a filter, blend mode or a background job. A pixel bender kernel running as a background job (ShaderJob) runs on a true thread (rather than a PseudoThread) and is therefore faster. The only disadvantage here is that your background job must be programmable in pixel bender's language, Hydra.

Report abuse

Related recipes