2

What is the way to convert the following into lambda expression?

ThreadPool.QueueUserWorkItem(delegate
     {
        Console.WriteLine("Current Thread Id is {0}:",
         Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("I will be used as Callback");
      }
    );

1 Answer 1

5

You could definitely write this as a lambda expression:

// The underscore is simply a placeholder for the "state"
// parameter that the WaitCallback delegate expects - you could
// use any character but you must specify one as lamba expressions cannot
// omit parameters like anonymous functions can.
ThreadPool.QueueUserWorkItem((_) =>
    {
        Console.WriteLine("Current Thread Id is {0}:",
        Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("I will be used as Callback");
    });

But remember that a lambda expression has no meaning outside of your source code. The C# compiler will convert your lambda expression right back to the code you have now.

A lambda expression is simply syntactic sugar that you can use to express an anonymous function - the compiler will convert this to either an anonymous function or an expression tree.

Sign up to request clarification or add additional context in comments.

4 Comments

Andrew ,what is the use of "_" (underscore) ?
Sorry, yes it's in the comment. Basically you need to throw something in there to be a placeholder.
The (_) => ... parameter would be more self-explanatory as state => ....
FYI, you don't need those parentheses around the underscore. You can just do: ThreadPool.QueueUserWorkItem( _ => { /* block omitted */ });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.