Home > Software engineering >  In HttpContent, why ReadFromJsonAsync is an async method?
In HttpContent, why ReadFromJsonAsync is an async method?

Time:12-21

I'm having a doubt about HttpContent.ReadFromJsonAsync (HTTP Framing

Mozilla documentation for HTTP Messages

In C#, the response object can be returned from a request as soon as all of the header frames have been received.

Why not just wait for all the data in the first place?

The request content could be massive! Imagine you want to download a 4Gb image, and save it to a file on the local PC. If the HTTP implementation waited for all the data frames to be received, you would end up using at least 4Gb of RAM to buffer the data.

Instead of waiting for the data frames, the content is exposed through a Stream. Data is appended to a buffer, and is read from the buffer by the application on demand. Reading from the stream is an asynchronous operation, because you may be waiting for more frames to be received. The key difference here is that the buffer can have a relatively small size limit. If the response contains more data than can fit into the buffer, you'll have to read from the stream multiple times - which is normal use of the Stream API.

  • Related