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

I am a community lead in this group.


Simplified syntax
Submitted by Janco Wolmarans on Mon, 01/11/2010 - 13:55.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
Submitted by Werner Moecke on Tue, 07/20/2010 - 15:16.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. :)
Post new comment