Reputation: 80
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:
() =>
mean?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");
}
});
};
Upvotes: 4
Views: 265
Reputation: 6920
()
is your list of parameters, in your case empty or none, that is getting passed into the anonymous function following the =>
operator. The =>
gets its name from Lambda calculus.
It depends on how you are calling your tasks in the list. This is simply a List<Task>
with Tasks in it. In order to execute your tasks you would need to do something like this:
foreach (Task t in myTasks) {
t.RunSynchronously(); // in this case the tasks would run synchronously
}
Upvotes: 0
Reputation: 5801
()
- 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).
Upvotes: 4
Reputation: 6611
()=>
is an Action
- an expression with no parameters.
These tasks have not been started so (currently) will never complete...
Upvotes: 0
Reputation: 13696
You're probably used to seeing lambda functions like x => DoSomething(x)
. That's actually shorthand for (x) => DoSomething(x)
- the initial (x)
represents the parameters to the function, the same as the (x)
in DoSomething(x)
. does.
In this case, there are no parameters, so it uses ()
, the same as a regular function would be DoSomething()
.
As for the Task
s, they'll run in parallel once started, unless you explicitly wait until each one is done before starting the next.
Upvotes: 2
Reputation: 32541
Upvotes: 0
Reputation: 572
() would be similar to the parameters the function takes, and I believe that tasks are executed asynchronously => Points to the body of the function
Upvotes: 0
Reputation: 116401
The () =>
syntax just means that there's no named input to the lambda. It is like calling a method that takes no parameters.
As for the code the tasks are just created but never actually started, so they don't run in the code shown. I assume the list is enumerated and the tasks started somewhere else.
Upvotes: 4