So i’m trying to learn how to program with Task’s and i’m doing an exercise:
public static int ReturnFirstResult(Func<int>[] funcs)
{
Task[] tasks = new Task[funcs.Length];
for (int i = 0; i < funcs.Length; i++)
{
tasks[i] = CreatingTask(funcs[i]);
}
return Task<int>.Factory.ContinueWhenAny(tasks, (firstTask) =>
{
Console.WriteLine(firstTask.Result);
return ***????***;
}).***Result***;
}
private static Task CreatingTask(Func<int> func)
{
return Task<int>.Factory.StartNew(() => { return func.Invoke(); });
}
I’m giving a array of Funcs to run, the ideia is to returns the result of the first that func that was done.
The problem is that the field Result is not available…
What i’m missing here?
You’re returning
Taskfrom theCreatingTaskmethod – you need to returnTask<int>, and then changetasksto beTask<int>[]instead ofTask[].Basically,
Taskrepresents a task which doesn’t produce a result – whereasTask<T>represents a task producing a result of typeT. In your case, everything throughout your code returnsint, so you needTask<int>everywhere.