Jacko
Jacko

Reputation: 13195

c# BeginGetResponse: is there any reason to read bytes asynchronously in response callback?

The MSDN sample code for BeginGetResponse has two asynchronous calls, one to get the response, and one to read from the response buffer:

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse.aspx

See this line:

// Begin the Reading of the contents of the HTML page and print it to the console.
  IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);

My question is: what is the advantage here, vs. a synchronous read?

Thanks!

Upvotes: 2

Views: 460

Answers (2)

Jacko
Jacko

Reputation: 13195

Here is what I've gathered from further investigation: even though the callback is happening on a non-UI thread, the asynchronous read prevents this thread from blocking. While the thread is blocked, it cannot be re-used by the thread pool, and another concurrent request may cause the pool to create one more thread, which incurs some overhead.

Upvotes: 2

Haojie
Haojie

Reputation: 5713

I believe the advantage is that you can still do stuff with your UI Thread after a asynchronous call

Upvotes: 1

Related Questions