3

I am trying to asynchronously complete four tasks and when they are all complete, append them to an object and return it.

Here is my code:

Task[] tasks = new Task[4];
tasks[0] = wtData.GetHFServiceData(wtTransfreeeId);
tasks[1] = wtData.GetTLServicesData(wtTransfreeeId);
tasks[2] = wtData.GetHMAServiceData(wtTransfreeeId);
tasks[3] = wtData.GetHSServiceData(wtTransfreeeId);

Task.WaitAll(tasks);

The problem is, since Task[] has no Result method, I have to define a type like Task<MyType>[]. But, each of the four tasks above return a different type.

How can I wait until all tasks are complete before adding them to my combined object and returning it?

user1477388
  • 20,790
  • 32
  • 144
  • 264

1 Answers1

6

You have to store them as Task<T> before you put them into an array.

Task<YourType1> task1 = wtData.GetHFServiceData(wtTransfreeeId);
Task<YourType2> task2 = wtData.GetTLServicesData(wtTransfreeeId);
...
Task[] tasks = new Task[]{task1, task2, ...};
Task.WaitAll(tasks);

var result1 = task1.Result;//Access the individual task's Result here
...

Avoid blocking wait, consider using Task.WhenAll with await if you're in .Net 4.5. otherwise Task.Factory.ContinueWhenAll is another option.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • Thanks, seems to work. Is there a way to do this inline like `Task[] tasks = new Task[] { (Task>)wtData.GetHFServiceData(wtTransfreeeId) };`? I tried that but it doesn't work. – user1477388 Sep 26 '14 at 19:27
  • What is the return type of `GetHFServiceData`? What error you get? – Sriram Sakthivel Sep 26 '14 at 19:28
  • The return type is `Task>` and the error is when I try to access the result by using `tasks[0].Result` is says that Task[] has no such method. – user1477388 Sep 26 '14 at 19:32
  • 1
    No, if they are different types you can't do that. You'll have to declare separate variables as I shown you. – Sriram Sakthivel Sep 26 '14 at 19:33
  • 1
    You should be able to put them into the array just fine, since they have a common base type. Fetching the `Result` property requires the specific type, though. – Ben Voigt Sep 26 '14 at 19:42