Reputation: 1063
This is sample code from Microsoft, explaining how chaining tasks works:
using System;
using System.Threading.Tasks;
1. public class Example
2. {
3. public static async Task Main()
4. {
5. // Execute the antecedent.
6. Task<DayOfWeek> taskA = Task.Run( () => DateTime.Today.DayOfWeek );
7. // Execute the continuation when the antecedent finishes.
8. await taskA.ContinueWith
9. ( antecedent => Console.WriteLine("Today is {0}.", antecedent.Result) );
10. }
11. }
On line #9 ContinueWith
is passed a lambda expression.
My question is: how does the compiler know what antecedent
is and where to take it from? I mean, taskA
has a Result
property and can be passes as an argument, but does the compiler just go around the code and when it sees the first thing that can be passed it picks it?
Upvotes: 0
Views: 73
Reputation: 26917
Lambda parameter inference matches the parameter antecedent
to the Task<DayOfWeek>.ContinueWith(Action<System.Threading.Tasks.Task<DayOfWeek>> continuationAction)
continuationAction
parameter, and so sets the type of antecedent
to Task<DayOfWeek>
.
ContinueWith
passes the completed Task<DayOfWeek>
taskA
as the parameter to the lambda because that is what it is defined to do: see the documentation.
Upvotes: 0
Reputation: 12052
The Task
ContinueWith
method has specific overloads that define what kind of function it accepts as the parameter which defines the function parameters. You have a lot of options so check the official documentation for details.
The sample uses the ContinueWith(Action<Task<TResult>>)
the most basic overload where you can see the parameter is specified in the method definition this is how the Action
parameter type is defined. You call ContinueWith
on a Task<DayOfWeek>
so the TResult
type is DayOfWeek
and the methods signature inferred looks then like this ContinueWith(Action<Task<DayOfWeek>>)
for this case.
Upvotes: 2