Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpret c# lambda syntax

I have a general understanding of Lambda expressions but not sure what the () => syntax means. This code appears to return a list of Task items but I'm unsure how it executes or how to interpret what it means.

Can someone tell me:

  1. what does () => mean?
  2. It appears that each of the new Task blocks are executed sequentially?
 private DateTime? _myTime = null;
 private DateTime? _theirTime = null;
 private bool _okToProcess = true;

 List<Task> myTasks = new List<Task>
            {
                   new Task( () => 
                    {
                        _myTime = GetMyTime();
                    }),

                     new Task( () => 
                    {
                        _theirTime = GetTheirTime(); 
                        _okToProcess = _myTime > _theirTime;                                         
                    }),

                new Task(() => 
                    {
                        if (_okToProcess)
                        {
                           WriteToMyLogStep("We are processing");
                        }
                        else
                        {
                           WriteToMyLogStep("We are NOT processing");
                        }
                     });
            };
like image 452
MikieIkie Avatar asked Dec 26 '22 08:12

MikieIkie


1 Answers

() - represents the parameters taken by the anonymus method,

=> - is generally read goes to and points to the anonymus methods body that uses those parameters (if any provided).

In your case the lamda expression is the same as:

 delegate() {  _myTime = GetMyTime(); }

As for the Tasks they are just added to a list, they are not executed. How they will be executed depends on how you want to execute them in the future. (maybe in a loop on the same thread or maybe on different threads).

like image 67
Freeman Avatar answered Jan 08 '23 07:01

Freeman