I discovered some new C# syntax and do not understand what it means. Here is the syntax-related code:
1)
BeginInvoke(new Action(() =>
{
PopulateUI(ds);
}));
2)
private void OnFormLoad()
{
ThreadPool.QueueUserWorkItem(() => GetSqlData());
}
What is the meaning of new Action()
and what is the meaning of the =>
symbol?
The syntax of ThreadPool.QueueUserWorkItem
was ThreadPool.QueueUserWorkItem(new WaitCallback(PrintOut), "Hello");
but here it shows ThreadPool.QueueUserWorkItem(() => GetSqlData());
, so how does it work? Why is WaitCallback
missing? Please explain in detail.
Thanks a lot.
The difference really is that a lambda is a terse way to define a method inside of another expression, while a delegate is an actual object type.
Lambda expressions, or just "lambdas" for short, were introduced in C# 3.0 as one of the core building blocks of Language Integrated Query (LINQ). They are just a more convenient syntax for using delegates.
The callback function takes two arguments: an Error and a response. When you call it, Lambda waits for the event loop to be empty and then returns the response or error to the invoker.
You can pass methods as parameters to a delegate to allow the delegate to point to the method. Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword.
As others have said, it is a lambda, which is basically an anonymous (unnamed) local function.
This might make a bit more sense if you look at some similar code that doesn't use lambdas:
// With a lambda
private void OnFormLoad()
{
ThreadPool.QueueUserWorkItem(() => GetSqlData());
}
// Without a lambda
private void OnFormLoad()
{
ThreadPool.QueueUserWorkItem(ExecuteGetSqlData);
}
private void ExecuteGetSqlData()
{
// If GetSqlData returns something, change this to "return GetSqlData();"
GetSqlData();
}
As for the other code, normally you shouldn't have to do new Action
. The problem is that the BeginInvoke
method takes a Delegate
, which is sort of old school, and breaks how most new code works.
With newer code (that takes something like Action
, or a specific type of delegate, like WaitCallback
), you either write a lambda, or simply give the name of a function inside your class. The example code I wrote above demonstrates both of these.
Also note that if you see something like: (Action) (() => Blah())
, it is pretty much the same as new Action(() => Blah())
.
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