Parameter to QueueUserWorkItem with a lambda expression?

2.1k Views Asked by At

In following code, what does the parameter 's' stand for? Can we not just omit 's' since its not being used in the method, so we have an anonymous method with no parameter like () => ...?

ThreadPool.QueueUserWorkItem((s)=> 
{
 Console.WriteLine("Working on a thread from threadpool");
});

UPDATE 1:

According to the accepted answer, the anonymous method is just a replacement for the normal WaitCallback delegate method like the one in ocd below, that is needed by QueueUserWorkItem as a parameter to it. Therefore, 's' should be of object type, since its a parameter to the ThreadProc method.

void ThreadProc(Object stateInfo) {
   // No state object was passed to QueueUserWorkItem, so  
   // stateInfo is null.
    Console.WriteLine("Working on a thread from threadpool");
 }
1

There are 1 best solutions below

7
On BEST ANSWER

The C# 2.0 syntax for anonymous delegates allows omitting the parameter list, in which case it will match any set of (non-ref non-out) parameters and ignore them.

ThreadPool.QueueUserWorkItem(delegate {
   Console.WriteLine("Working on a thread from threadpool");
});

Note that delegate {} is different from delegate () {}

The lambda syntax, on the other hand, doesn't work without a parameter list provided.