Label Cloud

Monday, May 07, 2007

Asynchronous ForEach and Funky Anonymous Delegates

I was working with some code based on an excellent article on multi-threaded technics in the May 2007 MSDN Magazine. One of the code snippets that was provided is a ForAll routine. For my use, I simplified it a little from the article. The new code snippet is attached

private static void ForAll<T>(IList<T> data, Action<T> a)
{
CountdownLatch latch = new CountdownLatch(data.Count);

for (int i = 0; i < data.Count; i++)
{
int idx = i;
ThreadPool.QueueUserWorkItem(delegate
{
a(data[idx]);
latch.Signal();
}
);
}
latch.Wait();
}

One of the interesting points in the code is the


int idx = i;

It is required, and without it, the delegate will use the value of i that is currently in use by the for loop that surrounds it.


Share/Save/Bookmark

1 comment:

mlk said...

Nice - could easily be a simple interview question for candidates who claim they know multithreading or that (and I've heard this) the framework handles it all now.

Just change the idx = i and ask "What's wrong with this code?"

Directory of Computers/Tech Blogs