1

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 Answer 1

4

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.

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

7 Comments

When I check if 's' is null within the anonymous method, it is null. So its confusing why 's' is needed?
@Sunil: It is needed because it is part of the System.Threading.WaitCallback type.
I can run a Task like this: Task.Run (()=> { DoThis();}), which allows a method without any parameters. Sorry its not making sense.
So its the parameter of WaitCallback type that is normally passed to QueueUserWorkItem method?
Yes, QueueUserWorkItem requires a WaitCallback delegate. So the lambda or anonymous delegate has to be compatible with it. And WaitCallback has one parameter.
|

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.