Attention: We are retiring the ASP.NET Community Blogs. Learn more >

ThreadPool.QueueUserWorkItem with Anonymous Types

I thought this blog post by Matt Valerio was good, and it gave me a few ideas to use in a current test project. He wrote a helper method to be able to use anonymous types when calling a delegate or lambda in the ThreadPool:

public delegate void WaitCallback<T>(T state);

public static class ThreadPoolHelper
{
    public static bool QueueUserWorkItem<T>(T state, WaitCallback<T> callback)
    {
        return ThreadPool.QueueUserWorkItem(s => callback((T)s), state);
    }
}

And his example code for using this method:

ThreadPoolHelper.QueueUserWorkItem(
    new { Name = "Matt", Age = 26 },
    (data) =>
    {
        string name = data.Name;
        int age = data.Age;
        // Long-running computation
    });

 

Cute, eh?

No Comments