Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadPool.QueueUserWorkItem -- is new WaitCallback() required?

90% of examples I see, including MSDN use this syntax:

ThreadPool.QueueUserWorkItem(new WaitCallback(MyCallback));

the other 10% use:

ThreadPool.QueueUserWorkItem(MyCallback);

Where MyCallback is a static function, in both cases.

The compiler doesn't give an error and the code appears to work either way. Is there some danger with not creating a new WaitCallback object and just passing the function directly?

I ask because I'm trying to locate some bugs in my code, which I'll address with more specific questions once I narrow it down, but also this general question because I've always been curious and couldn't find any answers. The closest I found was this:

http://msdn.microsoft.com/en-us/library/4yd16hza%28v=vs.90%29.aspx

Which states:

"Visual Basic users can omit the WaitCallback constructor, and simply use the AddressOf operator when passing the callback method to QueueUserWorkItem. Visual Basic automatically calls the correct delegate constructor."

...but doesn't actually say "C# users MUST use the constructor", and I'd also like to know why/details. I'm using .NET 3.5.

like image 837
eselk Avatar asked Feb 17 '23 00:02

eselk


1 Answers

ThreadPool.QueueUserWorkItem(new WaitCallback(MyCallback));

and

ThreadPool.QueueUserWorkItem(MyCallback);

are equivalent and are compiled to the same byte code. The compiler inserts the new WaitCallback call for you.

From MSDN:

Del<int> m1 = new Del<int>(Notify);

C# version 2.0 has a new feature called method group conversion, which applies to concrete as well as generic delegate types, and enables you to write the previous line with this simplified syntax:

Del<int> m2 = Notify;
like image 149
dtb Avatar answered Mar 04 '23 04:03

dtb