Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threading.Tasks.Task' does not contain a definition for 'Result'

Tags:

c#

.net

task

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?

like image 976
RSort Avatar asked Jul 04 '12 17:07

RSort


People also ask

What is Task in threading?

The Thread class is used for creating and manipulating a thread in Windows. A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel. The task can return a result.

What is the data type of the result property of the Task class?

The Task<T> class has a Result property of type T that contains whatever you pass back with return statements in the method. The caller generally retrieves what's stored in the Result property implicitly, through the use of await .

What is Task result in C#?

task.Result is accessing the property's get accessor blocks the calling thread until the asynchronous operation is complete; it is equivalent to calling the Wait method. Once the result of an operation is available, it is stored and is returned immediately on subsequent calls to the Result property.

Why we use using system threading tasks in C#?

Tasks Namespace. Provides types that simplify the work of writing concurrent and asynchronous code. The main types are Task which represents an asynchronous operation that can be waited on and cancelled, and Task<TResult>, which is a task that can return a value.


1 Answers

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.

like image 134
Jon Skeet Avatar answered Oct 15 '22 09:10

Jon Skeet