My Windows mobile application crashes sometimes with an exception that happens in the finalizer of System.Net.HttpReadStream
.
It only happens sometimes, but then it brings down the whole program. Is there anything I can do to make the program continue when such an internal finalizer throws? Or alternatively, how can I prevent such an error?
Here's the stacktrace of the exception (not complete, since I have to type the whole thing...
ObjectDisposedException
at System.Threading.Timer.throwIfDisposed()
at System.Threading.Timer.Change(UInt32 dueTime, UInt32 period)
at ...
at System.Net.ContentLengthReadStream.doClose()
at System.Net.HttpReadStream.Finalize()
The calling code is:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(actionUrl);
request.AllowAutoRedirect = true;
request.AllowWriteStreamBuffering = true;
request.Method = "POST";
request.ContentType = "application/json";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, myRequestObject);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
JsonSerializer serializer = new JsonSerializer();
MyResultObject result = (MyResultObject)serializer.Deserialize(reader, typeof(MyResultObject));
return result;
}
}
Update
The calling code above is fine. The problem was caused by another
HttpWebRequest
where the response was not disposed. So remember, always dispose the response object, but especially in Compact Framework since it can bring down your whole application!