Reputation: 541
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?
Upvotes: 35
Views: 30507
Reputation: 89160
You will get this error if you're trying to use .Result
on a Task
object. This might be because you meant to use Task<T>
. But, if you want meant to use Task
and you want it to return without using await
then Task
is like void
and does not have a result. You can use .Wait()
instead. This returns void
.
Upvotes: 8
Reputation: 1499870
You're returning Task
from the CreatingTask
method - you need to return Task<int>
, and then change tasks
to be Task<int>[]
instead of Task[]
.
Basically, Task
represents a task which doesn't produce a result - whereas Task<T>
represents a task producing a result of type T
. In your case, everything throughout your code returns int
, so you need Task<int>
everywhere.
Upvotes: 59