AccessViolationException in StreamReader.ReadToEnd()
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.AccessViolationE开发者_JAVA百科xception: 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
精彩评论