Here's a slightly more sober use of workers: performing aggregate functions against vectors of numbers. I think in a normal use case, this sort of computation would happen on a server, but now there's a second option.
I've created Vector Cruncher to do this aggregation and hide all the worker code from the developer. My AsyncVectorCruncher class has a source property which is its vector of numbers and, in this proof-of-concept, two asynchronous methods:
- randomise(count:int) - populates the source with count random integers between 0 and 100
- calculateAggregates() - populates the aggregateValues property of the AsyncVectorCruncher with the sum, average, minimum and maximum.
On my machine, running calculateAggregates() against a vector of a million elements takes around 2.5 seconds.
AsyncVectorCruncher invokes methods on the VectorCruncherManager. This is where the worker is created and messages to and from the worker are handled.
The VectorCruncherManager keeps a list of pending messages, the demo application kicks off firing 25 randomise requests and 25 calculate aggregate requests and these are handled in a FIFO manner by sending a message to the worker.
The VectorCruncherWorker does the hard work when it receives a message over the message channel, it returns the result to the VectorCruncherManager which, in turn, passes the result to the AsyncVectorCruncher using a callback function pattern.
The proof-of-concept demo contains a randomise button that creates 25 AsyncVectorCruncher instances each containing up to two million elements each. Pressing the calculate aggregates button populates the data grid with the aggregate functions.
The main MXML, VectorCruncherDemo, shows how simple the implementation is. The developer doesn't have to have any knowledge of workers.
The demo application lives here and the source code is available here.