使用HttpWebRequest和StreamReader下载网页时出现未处理的异常

时间:2010-08-25 20:08:33

标签: c# exception-handling httpwebrequest

这是一个使用.NET 4.0的C#应用​​程序。

背景

我一直在尝试优化从多个Web服务器下载文件的应用程序的一部分。除了偶尔出现远程计算机关闭连接的情况外,一切都运行良好。我认为这可能是由于各种因素造成的,包括网络问题,电源问题等。我想在连接关闭的情况下跳过下载。但是,目前该应用程序会导致由AppDomain.CurrentDomain.UnhandledException的处理程序拾取的异常。堆栈跟踪如下:

堆栈追踪:

Unable to read data from the transport connection:
An existing connection was forcibly closed by the remote host.
at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.IO.StreamReader.ReadBuffer() at System.IO.StreamReader.ReadToEnd()
at ProjectName.ClassNetwork.DownloadFile(String _IP, Int32 _Port, String _File)
at ProjectName.FormMain.GetIFile(ClassSensor Sensor, String& RawHolder, String[] FileData)
at ProjectName.FormMain.GetLegacyData(ClassSensor Sensor)
at ProjectName.FormMain.threader_Download(Object SensorObject)
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart(Object obj)

我最初使用了WebException和Exception的try / catch但它们没有捕获到这个特定的错误。我添加了最里面的try / catch以试图避免这个问题,但无济于事。我应该提一下,这个方法是由UI线程以外的线程调用的,这可能是try / catch块看起来不起作用的部分原因。请原谅我在多线程错误捕获时成为新手!

问题:

  • 如何改进此方法并正确处理中途连接失败的情况?

代码:

private static object[] DownloadFile(string _IP, int _Port, string _File)
{
    string uri = String.Format("http://{0}:{1}/{2}", _IP, _Port, _File);
    string Status = String.Empty;
    string Data = String.Empty;
    HttpWebResponse Response = null;

    try
    {
        HttpWebRequest webReq = (HttpWebRequest) WebRequest.Create(uri);
        webReq.Timeout = 10000;
        webReq.ReadWriteTimeout = 30000;
        Response = (HttpWebResponse) webReq.GetResponse();
        using (Stream dataStream = Response.GetResponseStream())
            if (dataStream != null)
                using (StreamReader reader = new StreamReader(dataStream))
                    try
                    {
                        // This line causes crashes if remote computer closes connection
                        Data = reader.ReadToEnd();
                    }
                    catch { } // Inner try/catch added to no avail
        Response.Close();
    }
    catch (WebException exc)
    {
        // Connection Error
        Status = exc.Status.ToString();
        Data = String.Empty;
    }
    catch (Exception exc)
    {
        // Other error
        Status = exc.Message;
        Data = String.Empty;
    }

    if (Response != null && Response.StatusCode != HttpStatusCode.OK)
    {
        Status = Response.StatusCode.ToString();
        Data = String.Empty;
    }

    return new object[] { Status, Data };
}

跟踪日志:

根据Feroze的建议,我跑了一个跟踪点,这就是结果:

System.Net Error: 0 : [2164] Exception in the
#46104728::UnhandledExceptionHandler - Stream was not readable.
System.Net Error: 0 : [2164]     at System.IO.BinaryReader..ctor(Stream input, Encoding encoding)
at ProjectName.ClassNetwork.DLStream(ClassSensor Sensor)
at ProjectName.ClassNetwork.DownloadFile(ClassSensor Sensor)
at ProjectName.FormMain.GetStreamFile(ClassSensor Sensor)
at ProjectName.FormMain.threader_Download(Object SensorObject)
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncctx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart(Object obj)

1 个答案:

答案 0 :(得分:1)

从堆栈中,我看不出这是一个你无法捕获的线程池线程抛出的异常。显然,从堆栈中看起来好像它是由你的应用程序线程调用的ConnectStream :: Read方法引发的。