tags:

views:

306

answers:

5

Hi

Completly new here with a question regaridng this post : http://stackoverflow.com/questions/738139/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.

+1  A: 

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.

Mark Byers
This was also a help. Thx.
Moberg
A: 

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.

Dario
I think what the OP is looking for is a plain english explanation of the lambda expression.
Robert Harvey
A: 

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

Frank Krueger
+7  A: 

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.

elder_george
Thanks. You made it very clear.
Moberg
A: 

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);
}
Konamiman