I am fetching data from an API with different dataset-identifiers as a query parameters. Earlier I tried a synchronous approach but its taking too much time.So I decided to create Tasks dynamically inside a foreach
loop for every dataset-identifier. Here is the code that I have written
foreach (var dataset in datasets)
{
Task task = new Task(() =>
{
using (var client = new HttpClient())
{
var urlParameters = $"?apikey={apiKey}&dataset={dataset}";
client.BaseAddress = new Uri(url);
HttpResponseMessage response = client.GetAsync(urlParameters).Result;
var yearlyDatasetResult = response.Content.ReadAsStringAsync().Result;
var datasetCsvHeader = yearlyDatasetResult.Split(new[] { '\r', '\n' })
.FirstOrDefault();
var headers = datasetCsvHeader.Split(';');
if (csvHeaders.Length < headers.Length)
csvHeaders = headers;
var content = yearlyDatasetResult.Substring(datasetCsvHeader.Length);
using (var file = new StreamWriter("C:\\xxxx\\xxxx\\source\\"
+ $"repos\\xxxx\\CSV\\{dataset}.csv"))
{
file.WriteLine(content);
}
}
});
task.Start();
tasksToWait.Add(task);
}
Task.WaitAll(tasksToWait.ToArray());
Console.WriteLine("All tasks completed");
My goal is to fetch all the CSV files and then write to my system without the headers via parallel running tasks, but I am getting System.AggregateException
. Could it be because of the blocking nature of this line?
HttpResponseMessage response = client.GetAsync(urlParameters).Result;
I am not able to guess the reason for this kind of exception, I do know that one of the tasks is failing and that's why I am getting this aggregated exception and that's the nature of Task.WaitAll(...)
, What could be the possible solution to this ?