Nested ussing: inner using disposes outer using ?

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi all,
I am using c# webserver from codeplex and I am implementing compression to gain performance. I have run into something that I dont understand well, maybe its my fault, maybe its something else.

I have nested using blocks
<pre class="prettyprint using (MemoryStream stream = new MemoryStream())
{
using (DeflateStream Compress = new DeflateStream(stream, CompressionMode.Compress))
{
Compress.Write(Encoding.ASCII.GetBytes(temp), 0, Encoding.ASCII.GetByteCount(temp));
}
byte[] compressed = stream.ToArray();
Response.Body.Write(compressed, 0, compressed.Length);
Response.AddHeader("Content-Encoding", "deflate");
Console.WriteLine("Compressed {0} from {1} to {2} bytes (deflate).",
Request.Uri.ToString(), temp.Length.ToString(), stream.Length.ToString());
}


[/code]
When I step throug this using the debugger, I see everything working fine until I step out of the nested using. When the debugger is on the line

<pre class="prettyprint byte[] compressed = stream.ToArray();[/code]
In the watch for stream.Length at that line I see "System.ObjectDisposedException", but the stream.ToArry() still executes correctly. Later the console.writeline throws an exception on stream.Length.ToString().
I thought that stream would not be disposed until the using for stream is exited.

Can someone tell me if the memorystream "stream" indeed will be disposed by the inner using block ? and if so, why is that ?
I can solve the exception very easy by moving the code into the inner using, thats not the big deal, but I would like to understand what is happening here. I also know that the using blocks can be taken together, thats not in the scope of my question.
Hope the community here has an answer why the inner using closes/disposes the outer using before it has ended.







View the full article
 
Back
Top