Reputation: 10219
I've run across some code in an ASP.NET app, and I'm wondering whether there is any practical difference between the following two snippets. Note, we are trying to send a request to a 3rd party endpoint and then use the response in what's rendered on the page.
Dim asyncResult As IAsyncResult = request.BeginGetResponse(Nothing, Nothing)
asyncResult.AsyncWaitHandle.WaitOne()
Using webResponse As WebResponse = request.EndGetResponse(asyncResult)
Using rd As StreamReader = New StreamReader(webResponse.GetResponseStream())
'code here
End Using
End Using
and this synchronous version:
Using webResponse As WebResponse = request.GetResponse()
Using rd As StreamReader = New StreamReader(webResponse.GetResponseStream())
'code here
End Using
End Using
According to this answer to another question, WaitOne blocks the thread. If so, is there really any advantage to doing that versus just using the synchronous method above? Am I correct in assuming that the thread processing the page will not be available to process other requests until this the method is finished either way?
Upvotes: 2
Views: 150
Reputation: 171216
That is a common anti-pattern. You get the worst of both worlds. No threads are unblocked and you add overhead.
Probably, the responsible person heard that using async APIs makes their app more scalable. If that was the case, why wouldn't GetResponse
be just implemented in terms of the Begin/End methods and always be scalable?
Async is all the rage at the moment and it is being misused all the time and even when used correctly it is often a waste of time on the server. Don't be surprised seeing stuff like this.
Upvotes: 1