使用HttpWebRequest和StreamReader下载网页时处理异常 [英] Unhandled exception while downloading web page using HttpWebRequest and StreamReader

查看:201
本文介绍了使用HttpWebRequest和StreamReader下载网页时处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is a C# app using .NET 4.0.

背景:

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

I have been trying to refine a portion of an app which downloads files from multiple web servers. Everything is working pretty well except for an occasional situation wherein the remote computer closes the connection. I assume this may be due to a variety of factors, including network problems, power problems, etc. I'd like to simply skip the download in the event that the connection closes. However at present the application causes an exception which is picked up by the handler for AppDomain.CurrentDomain.UnhandledException. The stack trace is as follows:

堆栈跟踪

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块似乎不工作。原谅我是一个新手,当涉及多线程错误捕捉!

I originally had the try/catch for the WebException and Exception but they didn't catch this particular error. I added the innermost try/catch in an attempt to avoid the problem, but to no avail. I should mention that this method is called by threads other than the UI thread, which may be partly why the try/catch blocks are not seeming to work. Forgive me for being a newbie when it comes to multi-threaded error catching!

问题:


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

代码

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的建议,我运行了一个跟踪点,这是结果:

Per Feroze's suggestion, I ran a trace point and this is the result:

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)


推荐答案

从堆栈中,我看不到这是一个由你无法捕获的线程池线程抛出的异常。显然从堆栈看来似乎被你的应用程序线程调用的ConnectStream :: Read方法抛出。

From the stack, I do not see how this is an exception thrown by a threadpool thread that you cannot catch. Obviously from the stack it seems as if it was thrown by the ConnectStream::Read method which was called on your application thread.

这篇关于使用HttpWebRequest和StreamReader下载网页时处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆