Thursday, February 11, 2010

Action Script Threads for Report Generation

My requirement: to create a complex report that may take several seconds to run without blocking the user's interaction with the application. In java the solution is simple: create a thread and invoke start(). In action script, it's a bit more difficult.

Action Script doesn't support threads directly out the the box but it is run in a multi-threaded framework, so I knew there must be a solution. I took some time to research how other flex developers were implementing Action Script threads and concluded that the best solution was to simply use the Timer class to create a new threads.

The timer class has an asynchronous event called TIMER_COMPLETE that is perfect for creating a bloated, heavy weight thread. But, if all you need is a separate thread to run while creating a huge report, this does the trick.

One of the practical considerations is that you will probably want a supporting class to encapsulate run parameters for each thread you create. For reports this works well because there is enough logic in each individual report to warrant its own class. And as long as the report class implements the timer start method then you are in good shape.

The simplest implementation looks like this:

public function start():void {
var timer:Timer = new Timer(1, 1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, run, false 0, true);

// override this base class to implement the run worker
protected function run():void {
// create the report or whatever you need...

Implement the run handler and you are set. The class can encapsulate any run time parameters that you require including a common dispatcher to dispatch a 'COMPLETE' event when the process is finished. Easy.

This is an acceptable work-around for a language that does not support threads right out of the box. But for the rare occasion that you really need a thread to enable interaction while a heavy-weight, time consuming task is running, this really does the trick.

Happy coding...