Thursday, April 7, 2011

Parallel operations in Silverlight

As far as I have been able to find out, Silverlight is fairly limited with respect to parallel and/or multithreaded computation support. The Parallel framework from .NET 4.0 is for example not present at all. However, it seems like the ThreadPool is a reasonable candidate for doing at least some work in parallel.

Based on the MSDN documentation for Silverlight, I have composed a very simple code snippet for separating larger computational work onto for example all available CPU cores.

int threads = Environment.ProcessorCount;
WaitHandle[] handles = new WaitHandle[threads];
for (int i = 0; i < threads; ++i)
{
handles[i] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(
delegate(object state)
{
...some long-running thread-able process...
((ManualResetEvent)state).Set();
}, handles[i]);
}
WaitHandle.WaitAll(handles);

I tested the above snippet on my eight CPU core computer, and repeated the same process throughout all iterations. The above parallel approach was then 2.5 times faster than the purely sequential one. Not a very impressive result, of course. There is certainly room for improvements, hopefully I will be able to implement more impressive speed-ups in due time.

No comments:

Post a Comment