I am trying to call many different web services at the same time and aggregating the data.
My intention is to create a Task for each web call, pass a shared container to each task, and store data from each call in the container. As long as I can get data from each web call into the shared container, I am happy.
I have created an example of what I'm trying to do - however, it sometimes crashes with an exception on the Task.WaitAll line: "One or more errors occurred. (Source array was not long enough. Check the source index, length, and the array's lower bounds. Parameter name: sourceArray)".
I am new to using async/await and multithreading.
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting tasks...");
List<Task> tasks = new List<Task>();
List<char> container = new List<char>();
for (int i = 0; i < 80; i++)
{
tasks.Add(LongTask(container));
}
Task.WaitAll(tasks.ToArray());
Console.WriteLine("Checkpoint 1.");
Console.WriteLine("Tasks Finished");
Console.ReadLine();
}
public static async Task<string> LongTask(List<char> container)
{
var client = new HttpClient();
var text = await client.GetAsync("http://www.google.com");
var myList = text.StatusCode.ToString().ToList();
container.AddRange(myList);
return text.StatusCode.ToString();
}
}
}