Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I use a lambda expression in place of a callback delegate?

Tags:

syntax

c#

.net

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.

like image 959
Thomas Avatar asked Dec 20 '10 06:12

Thomas


People also ask

What is the difference between lambda expression and delegate?

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.

Is lambda expression delegate?

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.

Is lambda a callback?

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.

Can delegate be used as callbacks?

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.


1 Answers

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()).

like image 82
Merlyn Morgan-Graham Avatar answered Sep 28 '22 23:09

Merlyn Morgan-Graham