0

I have a C# web application that makes a web service call, then renders a page for a browser. Following this advice, I chose to use System.Net.WebClient for the request because it had a succint interface and all the control I needed.

WebClient offers me async versions of all the download methods. Should I use them? I don't care if the current user waits. I need the web service result before I can render the page, and I have nothing else to be doing (for her) in the meantime. However I really do care if my server is tied up while one user's web service call completes. If this was javascript, a synchronous web request on the main thread would hold up at least the whole window. Is this the case in asp.net? For reasons outta my control, my web service request is at the bottom of a pile of 15 method calls. Dot I have to convert them all to async to see any advantage?

Community
  • 1
  • 1
bbsimonbb
  • 27,056
  • 15
  • 80
  • 110

1 Answers1

0

Generally speaking, async IO won't yield faster per-request response, but in theory it can increase throughput.

public async Task<IActionResult> YourWebApiMethod() {
  // at this point thread serving this request is returned back to threadpool and   
  // awailable to serve other requests
  var result = await Call3ptyService();
  // once IO is finished we grab new thread from thread pool to finish the job
  return result;
}

// thread serving this request is allocated for duration of whole operation 
public IActionResult YourWebApiMethod() {
  return Call3ptyService().Result;
}

You have only so-many threads in thread pool, if every single one is busy waiting for external service; your web server will stop serving requests. As for your particular problem - try it and you'll find out.

Ondrej Svejdar
  • 21,349
  • 5
  • 54
  • 89
  • I was starting to suspect. I hoped that WebClient might be clever enough to do async but hide it from me : park my pile, release the thread, wake things back up when the request returned. I see now that I'm hoping too much! – bbsimonbb Sep 15 '16 at 10:06