C # Threaded Tasks - cannot get return value from task array

I am trying to get the returned data from my task, it works fine if I use a single var, but when I use an array or arraylist, I don’t see the interface for RESULT in the available properties of the methods of the task object.

var task = Task<BookingListResponse> .Factory.StartNew(() => GetServicesFromApi(sc), TaskCreationOptions.LongRunning); tasks.Add(task); try { // Wait for all the tasks to finish. Task.WaitAll(tasks.ToArray()); } 

as you can see from the code, if I returned the tasks to the array and typed the tasks [1]. Result, it does not set the β€œresult”, if I refer to the task, then I can get it.

I'm sure I'm doing something stupid, so any help would be good.

greetings.

Pavel.


here is the full code:

 List<Task> tasks = new List<Task>(); // loop schemes and only call DISTINCT transit api URL's foreach (Scheme scheme in schemes) { if (url.ContainsKey(scheme.Url)) continue; url.Add(scheme.Url, 0); // add url. var sc = new ServiceCriteria(); sc.Url = scheme.Url; sc.CapacityRequirement = capacityRequirement; sc.DropOffLocation = dropOffLocation; sc.PickUpLocation = pickUpLocation; sc.PickUp = pickup; sc.TravelTime = travelTime; // Fire off thread for each method call. //tasks.Add(Task<BookingListResponse>.Factory.StartNew(apiAttributes => // GetServicesFromApi(sc), TaskCreationOptions.LongRunning)); var task = Task<BookingListResponse> .Factory.StartNew(() => GetServicesFromApi(sc), TaskCreationOptions.LongRunning); tasks.Add(task); } try { // Wait for all the tasks to finish. Task.WaitAll(tasks.ToArray()); var result = tasks[0].Result; } 

The result parameter is not displayed.

greetings.

+4
source share
2 answers

You need to specify your task list in Task<BookingListResponse> ...

So:

 var result = ((Task<BookingListResponse>)tasks[0]).Result; 
+10
source
 task.Result 

or

 tasks.First().Result 

must work

0
source

All Articles