Async - Multiple Operations and Loops

 



Suppose that instead of copying the HTTP response body to a file, you  wanted to process the data in the body. If the body is large, retrieving it is an operation that could require multiple, slow steps. This code loads web page gradually.

Multiple asynchronous operations

This now contains three await expressions. The first kicks off an HTTP GET request, and that operation will complete when we get the first part of the response, but the response will not be complete yet—there may be several megabytes of content to come.

This now contains three await expressions. The first kicks off an HTTP GET request, and that operation will complete when we get the first part of the response, but the response will not be complete yet—there may be several megabytes of content to come. This code presumes that the content will be text, so it wraps the Stream object that comes back in a StreamReader, which presents the bytes in a stream as text.3 It then uses that wrapper’s asynchronous ReadLineAsync method to read text a line at a time from the response. Because data tends to arrive in chunks, reading the first line may take a while, but the next few calls to this method will probably complete immediately, because each network packet we receive will typically contain multiple lines. But if the code can read faster than data arrives over the network, eventually it will have consumed all the lines that appeared in the first packet, and it will then take a while before the next line becomes available. So the calls to ReadLineAsync will return some tasks that are slow, and some that complete immediately. The third asynchronous operation is a call to Task.Delay. I’ve added this to slow things down so that I can see the data arriving gradually in the UI. Task.Delay returns a Task that completes after the specified delay, so this provides an asynchronous equivalent to Thread.Sleep. (Thread.Sleep blocks the calling thread, but await Task.Delay introduces a delay without blocking the thread.)