StreamReader.ReadToEnd() 中的 AccessViolationException
在 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
I'm sometimes getting a AccessViolationException when calling ReadToEnd() on a WebRequest response stream.
I create a background thread to do this operation, post the results back to the UI thread, and let the thread exit on its own. My app does this about once per minute. It seems to run fine for a few hours, and then randomly crash.
Can anyone help me understand why this is happening?
Thank you very much!
Code
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...
Exception
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论