views:

312

answers:

2

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!

+2  A: 

This thread describes a similar problem.

The problem could be that you are returning inside the second using block. This way the response object won't get closed.

kgiannakakis
Then everything I ever learned about the using keywork or try/finally would be wrong...
chris166
But I'm also using .NET CF 3.5 like in the thread you mentioned. At least I'm not alone in this ;)
chris166
To be honest I don't know what happens when you are returning inside a using block. Perhaps in that case the finalizer isn't called. Anyway, it is bad practice to do so. Move the return statement out of the using blocks.
kgiannakakis
I don't think it's bad practice. If you return only at the end, every function looks like plain old C. Even in C++ I returned from inside a method and let the compiler figure out which destructors to call on the way out
chris166
I mean that you do something like this: using {...} return result; and not using { ... return result; }
kgiannakakis
A: 

It turned out that it was another HttpWebRequest causing this. The code in my question was fine, but the dispose of the response was missing in the other place.

chris166