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.
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'.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With