merlin2011
merlin2011

Reputation: 75575

Why do we need both BeginGetResponse AND BeginRead?

I'm looking at the following reference for making asynchronous web requests with C#:

http://msdn.microsoft.com/en-us/library/86wf6409%28v=vs.100%29.aspx

When I build the sample code with only BeginGetResponse and EndGetResponse, my "asynchronous call" still takes hundreds of milliseconds to complete.

Can someone explain why the reading requires another asynchronous call, when the BeginGetResponse should already be on a separate thread?

Upvotes: 0

Views: 385

Answers (2)

Dmitry Frenkel
Dmitry Frenkel

Reputation: 1756

Because BeginGetResponse/EndGetResponse have to do with connecting to the Http endpoint (server may take some time to respond) while BeginRead/EndRead have to do with reading a potentially long response from the response stream.

Imagine that your response takes 10 seconds to produce on the server and the amount of data it spits out is, say, 10MB.

  • Without the first pair of Begin/EndGetResponse calls, your thread would be blocked for at least 10 seconds waiting for the first byte of the response to come back.

  • Without the second set of Begin/EndRead calls, your thread would be blocked while you are reading 10MB of data one network packet at a time (remember that TCP packets have limited size so it takes a while for all of them to arrive back on the client)

Upvotes: 5

Sergey Sirotkin
Sergey Sirotkin

Reputation: 1677

I think that is mapped to underlying socket operations. BeginGetResponse establishes connection to server (that's why it takes so long) and sends the request, while BeginRead waits for response data.

Upvotes: 2

Related Questions