Reputation: 2385
I have a web service which calls an external web service. The external service responds after 3-4 seconds.
Right now all the calls are synchronous, but does it make sense to use async calls instead (sample below)?
Will it help with performance (not keeping threads blocked)? Isn't the thread blocked on the first line of GetData()?
Thank you.
public class MyService : WebService
{
[WebMethod]
public string GetData()
{
string response = ExecuteRequest(externalUrl, someContent).Result;
return response;
}
private async Task<string> ExecuteRequest(string url, string content)
{
var httpResponse = await new HttpClient().PostAsync(url, new StringContent(content));
string responseStr = await httpResponse.Content.ReadAsStringAsync();
return responseStr;
}
}
Upvotes: 0
Views: 1127
Reputation: 1569
To answer your question: Yes, it does make sense to use async calls instead, but your example is not async. If you wanted to make it async you'd have to do something like this:
public class MyService : WebService
{
[WebMethod]
public async Task<string> GetData()
{
string response = await ExecuteRequest(externalUrl, someContent);
return response;
}
private async Task<string> ExecuteRequest(string url, string content)
{
var httpResponse = await new HttpClient().PostAsync(url, new StringContent(content));
string responseStr = await httpResponse.Content.ReadAsStringAsync();
return responseStr;
}
}
Upvotes: 1