如何实现流readtimeout属性

时间:2016-01-28 09:16:10

标签: c# .net stream httpwebresponse

我正在修复一个错误:应用程序将在下载过程中挂起5分钟而丢失网络连接。我需要做的是将停机时间减少到20秒。

log snippet:

Severe  2016-01-27 , 11:03:14
    在 HttpsDownload.doDownloadByHttps(FileDownloadInfo fileInfo, downloadingDelegate downDelegate)
    Message: Init method:GET

Info    2016-01-27 , 11:08:29
    在 HttpsDownload.writeToFile(FileDownloadInfo fileInfo, Stream stream, downloadingDelegate downDelegate, Boolean Clear)
    Message: Exception while reading from the response stream
    Exception:
        Message: time out
        Type: System.Net.WebException
           在 System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   在 HttpsDownload.writeToFile(FileDownloadInfo fileInfo, Stream stream, downloadingDelegate downDelegate, Boolean Clear)

代码段:

private void doDownloadByHttps(FileDownloadInfo fileInfo, downloadingDelegate downDelegate)
        {
                //code
                webResponse = (HttpWebResponse)webRequest.GetResponse();
                responseStream = webResponse.GetResponseStream();
                writeToFile(fileInfo, responseStream, downDelegate, bClear);
        }
private void writeToFile(FileDownloadInfo fileInfo, Stream stream, downloadingDelegate downDelegate, bool Clear)
        {
                int count = stream.Read(readBuffer, 0, BlockSize);
                while (count > 0) 
                {
                    //code
                    count = stream.Read(readBuffer, 0, BlockSize);
                }
        }

我认为根据日志在stream.Read中发生超时。因此,最简单的方法应该是stream.ReadTimeout = 20000,但显然我无法设置ReadTimeout属性。 可以想到的另一种方法是编写一个类覆盖ReadTimeout,如:

public class MyStream : Stream {
//code
public override int ReadTimeout { get; set; }
//code
}

但它并不是首选。有没有更好的方法来修复错误?

1 个答案:

答案 0 :(得分:1)

需要在类型为webRequest的{​​{1}}对象中设置超时。

检查出来:https://msdn.microsoft.com/en-US/library/system.net.httpwebrequest.readwritetimeout(v=vs.110).aspx