Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 731
Randof LoveBottom Avatar asked Dec 06 '10 13:12

Randof LoveBottom


People also ask

What C is used for?

C is a powerful general-purpose programming language. It can be used to develop software like operating systems, databases, compilers, and so on.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Why is C named so?

Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C".


1 Answers

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

So do:

var result = ((Task<BookingListResponse>)tasks[0]).Result;
like image 66
Tom Avatar answered Sep 22 '22 15:09

Tom