背景:
我一直在尝试完善一个应用程序的一部分,它可以从多个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)
代码:
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)