Friday, April 23, 2010

Uploading files with the .Net framework

The .Net framework has some very simple wrappers for performing http communication, but sometimes there are subtle aspects that introduce bugs.

One issue that I have recently discovered is the Timeout property, which has the following description on MSDN:
Gets or sets the time-out value in milliseconds for the GetResponse and GetRequestStream methods.

As I read that description, I get the impression that the call to GetRequestStream is blocked until a connection is made, or the Timeout occurs.

Unfortunately, this should be read as:
Gets or sets the time-out value for the completion of the request or response operation.

A simple code example:
HttpWebRequest req = WebRequest.Create("");
req.Timeout = 2 * 1000; //2 seconds
req.Method = "PUT";
using(Stream stream = req.GetRequestStream())
//This does not count towards the timeout,
// perhaps because the connection is not made until the first write
Thread.Sleep(5 * 1000);

//This does nothing, as the stream has the value cached
req.Timeout = 5 * 1000;

//This loop must finish before 2 seconds have passed!
// the timer starts when the first byte is written
{ /* Code that writes to stream */ }

No comments: