tags:

views:

185

answers:

3

I am using ThreadPool with the follwoing code:-

ThreadPool.QueueUserWorkItem
                (o =>
                MyFunction()
                );

I am not sure what does o=> does in this code. Can anyone help me out.

+11  A: 

It describes a lambda (anonymous) function. In this case it's a function that takes one argument, o, and then executes MyFunction (although in this case it's basically throwing the value of o away). It's equivalent to:

void Foo(object o) //We know that Foo takes an object and returns void because QueueUserWorkItem expects an instance of type WaitCallback which is a delegate that takes and object and returns void
{
  MyFunction();
}

ThreadPool.QueueUserWorkItem(Foo) // or ThreadPool.QueueUserWorkItem(new WaitCallback(Foo));

The type of o is inferred based on whatever QueueUserWorkItem expects. QueueUserWorkItem expects type WaitCallback so in this case o should be of type object because WaitCallback is delegate for methods with one parameter of type object that return void.

As for the meaning of this particular code fragment; you're basically adding a function (work item) to a queue that will be executed by one of the threads in the pool (when it becomes available). That particular code fragment just describes a nice, succinct way of passing in the function without having to go through the trouble of fully defining a class method.

Incidentally, I, and others, tend to read => as 'such that'. Some people read it as 'goes to'.

Rodrick Chapman
Just to clarify, => is the operator and o is the parameter being passed in. Have a peek at http://msdn.microsoft.com/en-us/library/bb397687.aspx for further details.
lzcd
@lzcd: I wouldn't call it an operator. It's just the syntax which separates the parameters from the body of the lambda.
Porges
If i understand correctly then if i want to pass some parameters to my function then i can do it like this:-ThreadPool.QueueUserWorkItem(o=>MyFunction(o));
Zeeshan Umar
@Zeeshan Yes, exactly.
Rodrick Chapman
+2  A: 

It's declaring an anonymous method. Basically, you are passing a method whose body is { MyFunction(); } as a parameter to the QueueUserWorkItem method. I haven't checked, but it should also be also equivalent to:

ThreadPool.QueueUserWorkItem(MyFunction);
Dario Solera
Not quite I don't think. QueueUserWorkItem expects a delegate that accepts one object as an argument; hence wrapping `MyFunction` in a lambda.
Duracell
+3  A: 

This is the C# syntax for a lambda expression.

It is in many ways an inline delegate definition. It saves you the tediousness of defining an extra function to use as the delegate target.

private object Target(object state) {
  MyFunction();
}

...
ThreadPool.QueueUserWorkItem(new WaitCallback(Target));
JaredPar