I am trying to call an async method from a synchronous method and it keeps bombing on the call to GetUsTraceApiHealth()
but with no errors. What is the problem?
Calling Method:
public ActionResult TestSSN()
{
try
{
var apiResponse = GetUsTraceApiHealth().GetAwaiter().GetResult();
string responseBody = apiResponse.Content.ReadAsStringAsync().Result;
return Json(responseBody, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
Method Being Called:
public async Task<HttpResponseMessage> GetUsTraceApiHealth()
{
using (HttpClient httpClient = new HttpClient())
{
try
{
string uri = $"https://trace.{ConfigHelper.SterlingDomain}health?deep";
HttpResponseMessage apiResponse = await httpClient.GetAsync(uri);
return apiResponse;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
}
TestSSN()
async as well? Then just await the call instead of using.Result
.TestSSN
async and have it return aTask<ActionResult>
. And use theawait
keyword instead of accessing.Response
. And don't take an exception, grab the exception's message and then throw a new exception. You'll lose valuable information that way. Just remove that try/catch altogether.catch
blocks are throwing away useful exception information and replacing it with less information. You should really just get rid of those entirely.Task.Result
unless you know what you're doing. If you have code that ensures you're in a setting where the task has already completed, then yes, but otherwise, no. Most likely you have a deadlock situation on your hands. Additionally, your catch block should just be removed, let the original exception propagate up the call stack instead. You're throwing away stack trace, exception type, any additional properties, etc.