Processing Without Blocking Execution in ActionScript 3.0


By daniel - Posted on 29 July 2008

I've been working on a project visualizing large datasets and had hit a familiar wall. I needed to parse row upon row of CSV data and it was causing the application to hang up or give the "this script is causing your computer to run slowly" message.

Since this isn't the first time I've encountered this situation, I decided to create a class for asynchronous parsing. AsynchronousProcessor lets you specify a processing step function to call repeatedly and a per-frame time limit.

The step function is then called over and over again until the time limit is reached. When the Flash Player moves to the next frame, the function is called several more times until the time limit hits again. This repeats for each frame until the step method returns true.

So instead of doing all the processing in one frame, it's divided across multiple frames, allowing other actions or animations to occur.

Using the Asynchronous Processor

The AsynchronousProcessor class requires a reference to the Stage and since DisplayObjects not in the display list don't have this reference, I'm using a small StageUtils class instead. This class simply stores a static reference to the Stage.

// set the stage variable used by the AsynchronousProcessor.  this
// statement could go in the main timeline
StageUtils.stage = stage;
 
// define the function that does parsing.  when parsing is complete
// the method should return true
function parseNextLine():Boolean
{
  var line:String = getLine();
  if (line == null)
  {
    // no more lines to parse
    return true;
  }
  else
  {
    parseLine(line);
    return false;
  }
}
 
// create a processor that calls parseNextLine repeatedly until complete
var processor:AsynchronousProcessor =
	new AsynchronousProcessor(parseNextLine, 400);
processor.start();

That's it. Comment below if you have any problems.