开发者

Wrapping stream within a stream - will the wrapped stream be disposed properly?

开发者 https://www.devze.com 2023-03-24 02:22 出处:网络
I don\'t know how to check it, for example: using (var stream = new StreamWriter(someStream)) { stream.Write(\"\");

I don't know how to check it, for example:

using (var stream = new StreamWriter(someStream))
{
    stream.Write("");
}

will this behave like this:

using (var stream1 = someStream)
{
    using (var stream2 = new StreamWriter(stream1))
         stream.Write("");
}

or if I'd wrap into GZipStream or any other stream... will the first example dispose every underlaying stream?

Update:

Finally it hit me - just implemented the Stream class myself:

class MyStream : Stream
{
    // fake stream implementation

    protected override void Dispose(bool disposing)
    {
        Console.WriteLine("disposing in my class");
        base.Dispose(disposing);
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyStream stream = new MyStream();
     开发者_开发百科   DoSomething(stream);
        stream.Dispose();

        Console.WriteLine("end of program");
    }

    private static void DoSomething(Stream stream)
    {
        using (var writer = new StreamWriter(stream))
        {
            Console.WriteLine("inside using statement");
        }

        Console.WriteLine("after writing");
    }
}

and the result:

inside using statement
disposing in my class
after writing
disposing in my class
end of program


Calling close on the top most stream cascades down and will close them all, but this is not recommended because it's hard to keep tabs on whats open and not. As the other answerer said, use the using blocks religiously.

Hope this helps!


You are mixing two concepts here.

The main one is nested using blocks, and in the 2nd sample you are using them correctly.

The second issue is nested/wrapped/linked Disposable classes. In the case of StreamWriter and Stream, the Writer will close the Stream. But you don't want to know that, just use the using pattern.

A small tip, the following alternative layout is easier to read and maintain. When adding GZipStream you will have 3+ nested using blocks.

using (var stream1 = File.Create(...))
using (var stream2 = new StreamWriter(stream1))
{    
         stream2.Write("");
}


No you can't rely on it disposing the underlying stream for any IDisposable objects (although in the case of the StreamWriter it is documented to do so). In general don't rely on it.

You should use nested using statements.

0

精彩评论

暂无评论...
验证码 换一张
取 消