I have the following function that call my API:
private async void applyMe(int id, string data)
{
string url = $"https://localhost:44382/api/isc/getdata?id=" + id + "&data=" + data;
ApiHelper.InitializeClient();
string _apiResult = await APIProcessor.LoadApi(url);
}
API Helper
public static class ApiHelper
{
public static HttpClient ApiClient { get; set; }
public static void InitializeClient()
{
ApiClient = new HttpClient();
ApiClient.DefaultRequestHeaders.Accept.Clear();
ApiClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/jason"));
}
}
APIProcessor
public class APIProcessor
{
public static async Task<string> LoadApi(string url)
{
using (HttpResponseMessage response = await ApiHelper.ApiClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
string _apiResult = await response.Content.ReadAsStringAsync();
return _apiResult;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
I want to call my API inside foreach loop as below
using (myEntities _context = new myEntities ())
{
foreach (var item in _context.items.Where(s => s.id >= 1 && s.id <= 500))
{
applyMe(item.id, item.data);
}
}
The API not calling yet because of async await :(
Please how can I solve this issue?
await getData(...?await applyMe(...the name of the function wasn't my point obviously. You need toawaitan async functionasync Taskall the way up, until you get to the UI event handler, then useasync void. So declareprivate async Task applyMe(...