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();
}

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 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 associated with the e-mail address you provide, it will be 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.
  • Syntax highlight code surrounded by the <pre class="brush: lang">...</pre> tags, where lang is one of the following language brushes: as3, applescript, bash, csharp, coldfusion, cpp, css, delphi, diff, erlang, groovy, jscript, java, javafx, perl, php, plain, powershell, python, ruby, sass, scala, sql, vb, xml.

More information about formatting options