开发者

BinaryReader.Read does not throw IOException when the connection is lost

I use HttpWebResponse.BeginGetResponse() method to make a request to my server. The request has AllowReadStreamBuffering set to false so that the data will not be buffered. In the "Request Complete" notification I do the following (no error handling code included):

HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(result);
BinaryReader streamReader = new BinaryReader(response.GetResponseStream());

try
{
    while ((readSize = streamReader.Read(buffer, 0, buffer.Length)) > 0)
    {
    ...
    }
}
catch (Exception)
{   // NEVER GET HERE!!
...
}

My problem is that I cannot detect connection errors during reading data from stream (during the while loop). The behavior is very strange: it finishes to read all data that the OS has in the cache and then returns 'readSize = 0' as in the case of "end of stream". I was expecting streamReader.Read() to throw an IOException exception but it does not! I tried to find a stream failed flag somewhere but it seems that there is none (Stream/BinaryReader/HttpWebResponse). Please help!

I tested this by using three scenarios and all had the same behavior:

  1. Using the phone-to-PC USB connection
    • Phone connected to Internet using the PC USB connection
    • After few streamReader.Read() successful calls I disable the PC network card
  2. Using 开发者_开发技巧WIFI connection
    • Phone connected to Internet using WIFI connection
    • After few streamReader.Read() successful calls I power off the WIFI router
  3. Using WIFI connection
    • Phone connected to Internet using WIFI connection
    • After few streamReader.Read() successful calls I remove WAN cable (so it has no Internet access).

Thank you! Mihai


If you are not getting an exception then one option is to check the number of bytes read against response.ContentLength

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜