Randof LoveBottom
Randof LoveBottom

Reputation: 131

C# Threaded Tasks - cannot get return value from array of tasks

I am attempting to get the return data from my task, it works ok if i use a single var, but when i use an array or arraylist, i do not see the interface for RESULT in the available properties 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 put the tasks back into an array and type tasks[1].Result, it does not expose 'result', if i access task then i can get it.

I am sure i am doing something silly, so any help would be good.

cheers.

Paul.


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 option does not show.

cheers.

Upvotes: 5

Views: 7334

Answers (2)

Tom
Tom

Reputation: 3374

You need to cast your list of Tasks into Task<BookingListResponse>...

So do:

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

Upvotes: 10

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47038

task.Result

or

tasks.First().Result

should work

Upvotes: -1

Related Questions