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