Inline methods with ThreadPool and WaitCallback
Slightly for my own memory (since I’ll forget in the future and at least it’s available here), but for an upcoming training session I’m 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 from thread");
Thread.Sleep(500);
Console.WriteLine("Bye from thread");
}));
Console.ReadKey();
}