Inline methods with ThreadPool and WaitCallback

Slightly for my own memory (since I will forget in future and at least it's available here), but for an upcoming training session which I am presenting, I wanted to be able to inline a method when using the .NET ThreadPool’s QueueUserWorkItem method which requires a WaitCallback pointing to a method. I did this using the lambda expression support in .NET 3.0+ and it looks like this:

static void Main(string[] args)
{
    Console.WriteLine("Starting up");

    ThreadPool.QueueUserWorkItem(new WaitCallback(f =>
    {
        Console.WriteLine("Hello for thread");
        Thread.Sleep(500);
        Console.WriteLine("Bye from thread");
    }));

    Console.ReadKey();
}

Simplified syntax

Visitor's picture

You can even simplify the code a little by completely omitting
new WaitCallback()
This works because the lambda expression already represents an anonymous delegate that matches the signature of the WailCallback delegate constructor. ;)

This was absolutely

Visitor's picture

This was absolutely brilliant! Just what I needed to make my Web Service Thread-friendly.
Loved the lambda-expression approach - I was struggling to use WaitCallBack(), because I kept getting it to complain about my method call not matching the delegate's expected signature.

Works a treat, thanks for sharing this simple, yet effective solution. :)

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account, used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

Free Visual Studio training
StackOverflowServerFaultSuperUser Loading my StackExchange stats...
I am a community lead in this group.
We discuss SharePoint, Office and all things IW.
Twitter
Loading my tweets...