开发者

What is => operator in this code

开发者 https://www.devze.com 2023-01-04 18:29 出处:网络
I am using ThreadPool with the follwoing code:- ThreadPo开发者_如何学Gool.QueueUserWorkItem (o =>

I am using ThreadPool with the follwoing code:-

ThreadPo开发者_如何学Gool.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.

  • http://msdn.microsoft.com/en-us/library/bb397687.aspx

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


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消