Webclient and HttpWebRequest - two "time-saving" classes can kill more time than they save.

WebClient and HttpWebRequest are two Microsoft .Net classes that appear to make web communication effortless.  This is undoubtedly true if the communication is a common type such as getting a web page or posting data to a web service.  However, when it comes to uncommon scenarios such as communicating with a web stream source on Windows Phone 7, it may simply do not do what it is supposed to do.

For example, Webclient.OpenReadAsync() may invoke the callback function when the response is not a standard HTTP one with common headers and a content body.  The Stream instance resulted from WebClient.OpenWriteAync may not write data until the WebClient is closed even the Flush method would not help in this case.  One odd behavior of both WebClient and HttpWebRequest is their mysterious data cache.  If they are used to get get data asynchronusly, they will keep reading data in the background regardless of whether the program reads the data.  If the program cannot catch up with the background reading, the buffer will explode to produce an OutofMemeory exception because they are like a mad data reading machines that do not know how to stop. 

Fortunately, there is the class Socket which involves more to use, but it offers maximum flexibility and control. It may take a few more minutes to write the code, but it may save many hours from experimenting with gray boxes like WebClient or HttpWebRequest and it works in scenarios where WebClient or HttpWebRequest simple do not.

(updated: 2011-12-24)

This article was updated on 17:51:48 2024-03-17