31

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?

RSort
  • 501
  • 1
  • 5
  • 7

2 Answers2

55

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thank you Jon, now i got it :) – RSort Jul 04 '12 at 17:34
  • Oh.. So having just a Task is more like void, so obviously we can't have void.result (kind of), but with Task we now are getting some value thus we can get the Result. Thanks Jon :) – Unbreakable Sep 07 '18 at 01:23
6

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.

Richard Garside
  • 87,839
  • 11
  • 80
  • 93