3

Completly new here with a question regaridng this post : ThreadPool.QueueUserWorkItem with a lambda expression and anonymous method

Specific this :

ThreadPool.QueueUserWorkItem(
    o => test.DoWork(s1, s2)
    );

Can somebody please explain what the 'o' is? I can see the (in VS2008) that it is a object parameter but I basically don't understand why and how.

5 Answers 5

10

ThreadPool.QueueUserWorkItem requires a WaitCallback delegate as argument.

This delegate type corresponds to void function of one argument of type Object.

So, full version of the call could be

ThreadPool.QueueUserWorkItem(
    new WaitCallback(delegate(object state) { test.DoWork(s1,s2); });
);

More concise would be

ThreadPool.QueueUserWorkItem(
    delegate(object state) { test.DoWork(s1,s2); };
);

Using C# 3.0 syntax we can write it in more short form:

ThreadPool.QueueUserWorkItem(
    (object state) => { test.DoWork(s1,s2); };
);

C# 3.0 lambda syntax allows to omit state's type. As this argument isn't really needed, it is also abbreviated to the first letter of its type.

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

Comments

1

From the documentation of QueueUserWorkItem, the first parameter is a WaitCallback with the following definition:

public delegate void WaitCallback(
    Object state
)

The definition of state is:

 Type: System.Object
 An object containing information to be used by the callback method.

So the first parameter of QueueUserWorkItem is a function which takes an object (an optional user state) and does something that returns void. In your code, o is the user state object. It is not used in this case, but it has to be there.

Comments

0

Just look it up: The o is a state object you may pass to the executed method using the overloaded version of QueueUserWorkItem. When you don't pass one explicitly, it's null.

This way useful in times when no lambda expression were available.

1 Comment

I think what the OP is looking for is a plain english explanation of the lambda expression.
0

o is a formal parameter to the lambda function. Its type is derived by the parameter type of QueueUserWorkItem.

Comments

0

The other answers are good, but maybe it helps if you see what is the equivalent without using neither lambda expressions nor delegate methods (that is, doing it the .NET 1 way):

void SomeMethod()
{
  //...
  ThreadPool.QueueUserWorkItem(new WaitCallback(TheCallback));
  //...
}

void TheCallback(object o)
{
  test.DoWork(s1, s2);
}

Comments

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.