Is it incorrect to use asyc await in a foreach loop? I get a WebException, The request was canceled.
The following is just a outline of the code I’m working on. Please let me know if this is not clear.
using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://xxx.xxx.com/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); try { var response = await client.PostAsJsonAsync("customers/xxxx/xxx/documents", requestMessage); response.EnsureSuccessStatusCode(); var returnValue = response.Content.ReadAsAsync<ResponseMessage>(); var hasDocuments = returnValue.Result.SearchResults.Any(); if (hasDocuments) { // HTTP GET client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*")); returnValue.Result.SearchResults.ForEach(async d => { response = await client.GetAsync(d.Self + ".pdf"); }); } } catch (Exception ex) { throw; } }