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?
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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With