I have implemented this code, since 2 weeks now. Since then I am trying to improve my code because sometimes the Task.Delay method is not enough to wait the third party API to send the correct http status code that I needed it. (They process is much longer than what I expected.)
var url = string.Format(_azureFormRecognizerConfig.RequestUrl, _azureFormRecognizerConfig.ResourceUrl, modelId);
var content = new StringContent(JsonConvert.SerializeObject(new { source = storagePath }), Encoding.UTF8, _azureFormRecognizerConfig.MediaType);
using (var httpClient = new HttpClient())
{
// Request headers
httpClient.DefaultRequestHeaders.Add(_azureFormRecognizerConfig.SubscriptionType, _azureFormRecognizerConfig.SubcriptionKey);
using (var response = await httpClient.PostAsync(url, content))
{
try
{
response.EnsureSuccessStatusCode();
responseLocationUri = response.Headers.GetValues("Operation-Location").FirstOrDefault();
}
catch (HttpRequestException ex)
{
_logger.Information($"Error in httpclient { ex.Message } ");
}
}
Task.Delay(20000).Wait();
using (var response = await httpClient.GetAsync(responseLocationUri))
{
try
{
response.EnsureSuccessStatusCode();
responseBody = await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException ex)
{
_logger.Information($"Error in httpclient { ex.Message } ");
}
}
_logger.Information($"Response headers { responseBody }");
}
As you can see in my code, I put a delay of 20,000 milliseconds (20seconds) just to handle the logic and expect that within that time the process is done and I can get the correct response and value.
Is there anyway, how can I improve this or make it work like a callback or something that I still didn't discover.
try-catchblock does not include theawait GetASynccall, youu may want to change it.Task.Delay(20000).Wait();UsingWait()on aTaskis asking for trouble. Since you're already in an async function, useawait Task.Delay(20000);instead.