Reputation: 3727
I'm implementing code from a developer that are using async functions.
Example:
public async Task<string> GetDataAsync(string jsonString = "")
{
string url = $"{this.url}";
using (HttpClient httpClient = new HttpClient())
{
using (StringContent body = new StringContent(jsonString, Encoding.UTF8, "application/json"))
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.accessToken);
using (HttpResponseMessage response = await httpClient.PostAsync(url, body))
{
switch (response.IsSuccessStatusCode)
{
case true:
return await response.Content.ReadAsStringAsync();
default:
throw new Exception($"Error calling url: {url}. HTTP status: {response.StatusCode}");
}
}
}
}
}
And I don't need, nor do I want, to call anything asynchronously. But the problem is that async functions is bubbling all the way up through my functions and so I can't just stop using it, and since HttpClient doesn't have a Post()
function to use instead of PostAnync()
then I feel stuck in this asynchronous cage.
Is there a trick or whatever to call an async function normally, stopping threading from bubbling up through all parent functions?
Or is the only solution to find a package without async functions?
Upvotes: 0
Views: 135
Reputation: 942
The short answer is - no, there's no generic way to make a synchronous function out of a a task-based asynchronous one.
The problem is that you don't know how it is implemented internally. Say, the asynchronous function is implemented using async
and it's running (partially) in the context of the primary thread. Then, if the caller code is trying to block the primary thread by a blocking call, then the async
function is blocked, too, which is causing a deadlock.
But, in your particular case you can try to create a new task, call the async
function from that task and take its result. There are good chances that it will work, but no guarantee (as mentioned above).
The code would look like this:
using (var response = Task.Run(() => httpClient.PostAsync(url, body).Result).Result)
{
...
}
Upvotes: 2