在WebRequest响应流上调用ReadToEnd()时,我有时会遇到AccessViolationException。
我创建了一个后台线程来执行此操作,将结果发布回UI线程,并让线程自行退出。我的应用程序每分钟执行一次。它似乎运行了好几个小时,然后随机崩溃。
任何人都可以帮助我理解为什么会这样吗?
非常感谢!
代码
String uri = ... ;
String data;
WebRequest request = WebRequest.Create(uri);
request.Timeout = (int) TimeSpan.FromSeconds(30).TotalMilliseconds;
using (Stream stream = request.GetResponse().GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
data = reader.ReadToEnd(); // <-- exception...sometimes...
异常
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at System.Net.UnsafeNclNativeMethods.OSSOCK.recv(IntPtr socketHandle, Byte* pinnedBuffer, Int32 len, SocketFlags socketFlags)
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, SocketError& errorCode)
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.IO.StreamReader.ReadBuffer()
at System.IO.StreamReader.ReadToEnd()
at // my code here