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;
}