0

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;
    }
}
Cosmin
  • 2,365
  • 2
  • 23
  • 29
  • Why not make `GetData` async? – Patrick Hofman Sep 14 '15 at 14:12
  • Wouldn't that require to modify the clients calling my service? – Cosmin Sep 14 '15 at 14:16
  • 1
    I'm not sure how deadlocked threads (http://stackoverflow.com/questions/13140523/await-vs-task-wait-deadlock) will help with performance :)... It is hard to get async methods called from synchronous code working correctly if you know what you doing and it is really bad idea if you don't. – Alexei Levenkov Sep 14 '15 at 14:16
  • 3
    No, there is no difference for clients - remote calls are always asynchronous in nature, so clients will not see any change in behavior. – Alexei Levenkov Sep 14 '15 at 14:19
  • Nobody can tell without knowing the load profile of the app. I'll link you my standard treatment of how to decide whether to go sync or async: http://stackoverflow.com/a/25087273/122718 Why does the EF 6 tutorial use asychronous calls? http://stackoverflow.com/a/12796711/122718 Should we switch to use async I/O by default? – usr Dec 07 '15 at 19:52

1 Answers1

1

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;
    }
}
Shazi
  • 1,490
  • 1
  • 10
  • 22