Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

c# - wrapping MemoryStream in a using

I've been told that System.IO.MemoryStream need not be wrapped in a using block because there is no underlying resource, this kinda goes against what i've always been told about streams ("if in doubt, use a using").

Is this true? Why then does MSDN example use one (summarized below)?

using(MemoryStream memStream = new MemoryStream(100))
{
            // do stuff
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The C# idiom is that if an object implements IDisposable then you use a using block. This will allow all resources being used by the object be disposed of properly. You're not suppose to know the implementation details of MemoryStream. What you do know is that it implements IDisposable so you should dispose of it properly. Further, you think that you know now that it doesn't need to free any resources but how do you know that in the future MemoryStream won't change its underlying implementation so that it does use resources that need to be freed using Dispose? You don't, so since it implements IDispoable you have more future-proof code by just using the pattern now. Second, what if you change your code in the future to use a different type of Stream that does have managed resources? By wrapping the MemoryStream in a using block now you reduce maintenance issues in the future; again, this is the correct way to use objects, and specifically Streams that implement IDisposable. Third, it's a clear way to signal to readers that you are done using the object; it's what readers of your code will expect to see when they see you are using objects that implement IDisposable. Finally, this is the current implementation of MemoryStream.Dispose:

protected override void Dispose(bool disposing) {
    try {
        if (disposing) {
            this._isOpen = false;
            this._writable = false;
            this._expandable = false;
        }
     }
     finally {
         base.Dispose(disposing);
     }
}

So, this marks the stream as closed, not-writable and not-growable. If somehow someone else got a hold of a reference to the same MemoryStream, it now becomes unusable to them which could be a good thing. But this is really the least important issue; the implementation details don't matter.

Use a using block because MemoryStream implement IDispoable. Don't not use a using block because you think that MemoryStream doesn't have any resources that need to be freed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...