1

I wish to use Tasks in C# to simultaneously load multiple data feeds from an online API. I've achieved this using tasks and currently use, the commented out code:

var task = Task.Run(() => LoadDocument("http://Website.com/" + ID + ".xml?key=" + API.BUSKEY));
Documents.Add(await task);

This code works, however is looped inside of a for loop and and waits for each individual task to complete before continuing to the next; making my use of tasks redundant.

Instead I want to use the Task.WaitAll command and only wait once all tasks have been started. However, I'm having the issue of then adding the output/ results of the tasks to the Documents List.

How can I use the Task.All command and then add all the output to the Documents list? Thank You.

   static void Main(string[] args)
    {
        List<long> Ids = new List<long>()

        for (int i = 0; i < 1000; i++)  //Populate 1000 different IDs.
        {
            Ids.Add(039027710001);  //In production these would be all different/ unequie.
        }

        var ListOfDocuments = Task.Run(() => LoadMultiple(Ids)).Result; 
    }

    public static async Task<List<XDocument>> LoadMultiple(List<long> IDs)
    {
        List<XDocument> Documents = new List<XDocument>();
        List<Task> Tasks = new List<Task>();

        foreach (var ID in IDs)
        {
            Tasks.Add(Task.Run(() => LoadDocument("http://Website.com/" + ID + ".xml?key=" + API.BUSKEY)));

            //This is what I originally had and worked. However waited for each task
            //var task = Task.Run(() => LoadDocument("http://Website.com/" + ID + ".xml?key=" + API.BUSKEY));
            //Documents.Add(await task);
        }


        Task.WaitAll(Tasks.ToArray());
        //This is what I want to work and add the idividual results to documents list ^^^

        return Documents;
    }


    public static XDocument LoadDocument(string URL)
    {
        XDocument LiveTimes = XDocument.Load(URL);
        return LiveTimes;
    }
samtrod
  • 271
  • 2
  • 13
  • 2
    As a side note: There is also an asynchronous version of `Task.WaitAll(...)` (which waits synchronously): `var myResult = await Task.WhenAll(...)`. – InvisiblePanda Jan 17 '18 at 09:11
  • Since you're waiting synchronously, you can just get the individual results from each `Task` when the method completes. But, what you really want to use is `WhenAll()`, which you can await, and which will return an array of the results. This is all documented perfectly well, but see marked duplicate for additional information. – Peter Duniho Jan 17 '18 at 09:22
  • 1
    you need to specify the return value in your tasklist: `List> Tasks = new List>();` Then after waiting you can simply return all `Result`s : `return Tasks.Select(x=>x.Result).ToList();` – Mong Zhu Jan 17 '18 at 09:25

0 Answers0