When do I need the `using` statement for Disposable elements? - c#

I know in the below case, using does its job to release the disposable element, i.e.
using (StreamReader sr = StreamReader(filename))
{
txt = sr.ReadToEnd();
}
However, does the same happen if I use it inline? As you see, there I don't define it as a variable:
txt = (StreamReader(filename)).ReadToEnd();

Defining or not defining a variable doesn't affect whether you need to dispose an object.
If an instance of an class which implements IDisposable is created, you should call Dispose on it when you're finished with it.
You can do that with using or manually calling Dispose - a using statement is usually more convenient and fool-proof.

Firstly, the dispose method exists to allow the developer of the class (in this case System.IO.StreamReader) to release any unmanaged resources they may be holding on to (and a lot of people use it for general cleaning up).
As a rule, if a class implements IDisposable (and therefore contains a Dispose method) it should most definitely be called.
The using statement you have used above would be compiled into the following:
//Very roughly your code sample
using (var sr = new StreamReader())
{
//Some code
}
//What gets spat out by the compiler
var sr = new StreamReader();
try
{
//Some code
}
finally
{
sr.Dispose();
}
As you can see, this pattern means that Dispose will be called regardless of whether the //Some code section throws an exception of not.
Essentially, it's a C# helper so that you don't have to write the safe code above to ensure disposal of disposable objects.
Because of the obvious benefits, the question should really be "When shouldn't you use using".

The same thing does not happen in your second example as is happening in the first example. In your second example, the StreamReader will become eligible for garbage collection immediately after that line executes because you're not storing it in a variable (so it'll go out of scope). The key word here is "eligible" - there's no guarantee of when the object will actually be cleaned up. So the second line of code will result in a lock on the file being "held" until the garbage collector gets around to garbage collecting the StreamReader.
On the other hand, if you call Dispose() on the StreamReader, it'll release the lock on the file immediately without waiting for the garbage collector.

Related

What is the difference between instantiation using "using" and a simple instantiation

I have been working on some code for a while. And I had a question:
What it the difference between these two codes ?
using (FORM formExemple = new FORM ())
{
formExemple.ShowDialog();
}
and
FORM formExemple = new FORM ();
formExemple.ShowDialog();
using calls the object's Dispose() method to clean up after itself when it's done. It usually handles things like closing open connections and/or freeing up memory. If you instantiate it otherwise, you have to do that manually. You can only use using on objects that implement the IDisposable interface, which ensures that a method Dispose() exists for the object.
The using block is used to automatically dispose of an object that implements IDisposable.
The first gets Dispose() called at the end of the block. The using block will also ensure that the object is properly disposed of in the case of an Exception.
The second doesn't and needs to be handled by the developer when they're sure that they will no longer need the object.
As ever, consult the documentation - either the MSDN C# guide for using statements or the C# specification (it's section 8.13 in the C# 5 specification).
The using statement can only be used with types implementing IDisposable, and it basically makes sure that whatever resource appears in the inital expression (the resource acquisition expression) is disposed at the end of the block, even if an exception is thrown. Your first code snippet is broadly equivalent to:
FORM formExemple = new FORM(); // I hope you don't *really* use these names
try
{
formExemple.ShowDialog();
}
finally
{
formExemple.Dispose();
}
There's a little bit more to it than that, mind you:
The scope of any variable declared in the resource acquisition expression is the using statement itself
It copes with null values
It copes with changes to the variable within the using statement (the original value is still disposed)
Basically, it makes it easier to clean-up resources which require timely disposal - network streams, file handles, database connections, graphics objects etc.
using is something you can use with objects that have implement the IDisposable interface. The reason to use using is once you are done with your form, you don't have to worry about any clean up, the Dispose method on Form will be called and everything will be cleaned up.
In your second example, Dispose is never called and the objects are still in memory and could be for awhile if the garbage collector doesn't recognize that it needs to clean it up.
The using-statement ...
using (Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
... is a syntactic shortcut (syntactic sugar) for the following pattern:
{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
(I took the the example from the link above)
... and therefore the difference between your two code-snippets the try + the call to IDisposable.Dispose() in the finally-block.
The using statement defines the scope for formExemple, the memory allocated for formExemple will be freed once outside the control of the using statement.

Is it better to use the [using] statement in C# or the [dispose] method? Does this apply to external (COM) objects?

What is better, the using directive, or the dispose directive when finished with an object?
using(FileStream fileStream = new FileStream(
"logs/myapp.log",
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
using(StreamReader streamReader = new StreamReader(fileStream))
{
this.textBoxLogs.Text = streamReader.ReadToEnd();
}
}
On the other hand, when I'm dealing with System.Net.Mail, I'm told I need to Dispose() of the object to release any stray locks.
Is there any consistent guidance? How do I tell what is more appropriate in a given situation for a given object?
The using statement (not directive) involves an implicit call to Dispose(), in a finally block. So there is no contradiction here. Can you link to that discussion?
The official definition of
using (x) { ... }
is
try ... finally if (x != null) x.Dispose(); }
What is better?
From a notational perspective, the using() { } block. Technically they are the same.
It's the same thing. Usage is simple, if you create the object and use it in only one method then use using. If you need to keep it alive beyond the method call then you have to use Dispose().
The runtime callable wrappers for COM objects don't have a Dispose() method.
There's no reason that I can think of to manually call Dispose(), other than in another implementation of Dispose() (for example in a class you've created that implements IDisposable) when you can wrap an object in a using block. The using block puts the creation and disposal of the object in a try/catch/finally block to pretty much gaurantee that the object will be disposed of correctly.
The compiler is more reliable than me. Or you. =)
MSDN documents the using statement and calls out where you can obtain the C# language specification where you can review section 8.13 "The using statement" (at least in the v4.0 reference it's 8.13) that gives a comprehensive explanation of the using statement and how to use it. The fifth paragraph gives the following:
A using statement is translated into
three parts: acquisition, usage, and
disposal. Usage of the resource is
implicitly enclosed in a try statement
that includes a finally clause. This
finally clause disposes of the
resource. If a null resource is
acquired, then no call to Dispose is
made, and no exception is thrown.
using(foo)
{
foo.DoStuff();
}
is just syntactic sugar for this:
try
{
foo.DoStuff();
}
finally
{
if(foo != null)
foo.Dispose();
}
So I'm not sure where the debate comes from. using blocks do call dispose. Most people prefer using blocks when possible as they are cleaner and clearer as to what is going on.
As long as the lifetime of the object is within a block of code, use using, if your object needs to be long lived, for example to be disposed after an asynchronous call you need to manually call Dispose.
A using block is way better than you of remembering the call to Dispose in all possible and impossible ways execution can leave a block of code.
using calls Dispose upon exit. using is better because it assures calling dispose.
using blocks automatically call Dispose() when the end of the block is reached.
There is one really important reason to use the "using statement" anywhere you can.
If the code that wrapped via using statement threw an exception, you could be sure that the "using object" would be disposed.

When should I use "using" blocks in C#? [duplicate]

This question already has answers here:
What are the uses of "using" in C#?
(29 answers)
Closed 8 years ago.
Are there particular instances where I should (or shouldn't?) be using "using" blocks:
using(SomeType t = new SomeType()){
...
}
Some objects need some action to be taken when you have finished with them. Usually this is because the object uses some kind of resource that needs to be disposed of. For example, if you have a file object of class File, and this object opens a file from the file system, the file in the file system will need to be closed again.
If you just left the file object, and forgot to call file.Close() it wouldn't be cleaned up until the Garbage Collector (GC) ran and worked out nothing was still using the file object. When the Garbage Collector runs should be left to the Common Language Runtime (CLR) to decide. If the GC doesn't run for quite a while after you have finished with the file, the file could remain open potentially for a long time. This can pose a big problem if there are many file objects, or if something wants to open a file, but can't because the file object you left is still hanging around.
To solve this problem, C# has the IDisposable interface. This has one method called Dispose. Classes that require some cleanup implement this Dispose method. This gives you a standard way for cleaning up any objects that use resources. There are a lot of classes that need to have Dispose called. The problem with this is that code gets covered with calls to Dispose, and they are tricky to follow because the place where you new'ed the object and call Dispose to clean it up are different. So, you had to look around the code a lot and be very careful to check there were calls to Dispose in the right place.
To solve this problem C# introduced the 'using' keyword. You can put a 'using' keyword around where you new an object, and this ensures Dispose will be called on it for you. It guarantees that Dispose will be called whatever happens... even if there is an exception thrown within the body of the using statement.
So, you should use 'using' when you want to be sure an object that allocates resources will be cleaned up.
using can only be used for objects that are declared on the stack, i.e. in a function. It doesn't work for objects that are declared as members of a class. For them, you have to call Dispose yourself. You may have to implement Dispose in your class so that in can call Dispose on any member objects it has that require it.
Common objects that need using called on them are: Files, Database connections, Graphics objects such as Pen and Brush.
Sometimes it is also used when you want two operations to happen together. For example if you want to write a log statement when a block of code is entered and when it exits you could write a log class that you could use like this:
using( Log log = new Log("Doing stuff") )
{
// Stuff
}
The constructor for the log class could be made to write out the message, and the Dispose method could also write it out. Implement the finalizer (~Log) to assert if the Dispose method doesn't get called to ensure the 'using' is remembered around the 'new Log'.
When the SomeType class implements IDisposable.
Use using whenever the type implements IDisposable, unless you're going to wrap it in a try/catch block anyway, then you might as well (depending on what look you prefer) use a finally block.
I see plenty of other answers indicated when you should have a using statement. I want to address when specifically should not have a using statement:
If you need to use your object outside of the scope of the current function, don't have a using block. Good example are a factory method that returns a database connection or a method that needs to return a datareader. In either of those cases if you create your object with a using statement it would be disposed before the method returned, and therefore not usable outside the method.
Now, you still want to be sure that those objects are disposed, so you still might want a using statement somewhere. Just don't include it in the method where the object is actually created. Instead, you can wrap the function call itself in a using statement.
When SomeType implements IDisposable.
That is a clue to you the developer that SomeType uses unmanaged resources that need to be cleaned up.
Example:
using(SqlConnection MyConnection = new SqlConnection("Connection string"))
{
MyConnection.Open();
//...
// 1. SQLConnection is a type that implements IDisposable
// 2. So you can use MyConnection in a using statement
// 3. When using block finishes, it calls Dispose method of
// SqlConnection class
// 4. In this case, it will probably close the connection to
// the database and dispose MyConnection object
}
You can create your own objects that implements IDisposable:
public class MyOwnObjectThatImplementsIDisposable : IDisposable
{
//... some code
public void Dispose()
{
// Put here the code you want to be executed when the
// using statement finish.
}
}
So you could use an object of MyOwnObjectThanImplementsIDisposable type in a using statement:
using(MyOwnObjectThatImplementsIDisposable MyObject = new MyOwnObjectThatImplementsIDisposable)
{
// When the statement finishes, it calls the
// code you´ve writed in Dispose method
// of MyOwnObjectThatImplementsIDisposable class
}
Hope this helps
In this context the using statement is handy for types that implement IDisposable. When the code block exits the scope of the using statement, Dispose() is called implicitly. It's a good habit when working with objects you want to dispose immediately after use.
One specific instance in which you should be careful using a using block is with a WCF Service Client.
As noted in this MSDN article, wrapping a WCF client (which does implement IDisposable) in a using block could mask any errors which result in the client being left in a faulted state (like a timeout or communication problem). Long story short, when Dispose() is called, the client's Close() method fires, but throws and error because it's in a faulted state. The original exception is then masked by the second exception. Not good.
There are various workarounds out there, including one in the MSDN article itself. Others can be found at IServiceOriented and blog.davidbarret.net.
I prefer the last method, myself.
If you want a summary rule. Anytime an object using IDisposable where you would not have a catch, use using. Using, essentially, is this pattern:
try
{
//instantiate and use object
}
finally
{
//dispose object
}
If you do not need a catch, using can save you typing, which is a good thing.
The primary rule is:
* Use USING statement when objects implements IDisposable interface.
This interface provides the Dispose method, which should release the object's resources. If this method is not invoked then the object will stay in memory as long, as CLR wants to perform garbage collection. If the programmer use the USING statement then on the end the object will be disposed, and all resources will be free.
It is very important that all resources that are no longer in use be free as soon as possible.
For more information about it just visit this link: microsoft
Maybe it is worth mentioning that underlying reason for adding “using” lo C# languge is following: some resources can be scarce enough that it doesn’t make sense to wait for GC to call IDisposable. For example, DB connections. If you use try/catch/finally you won’t end up with a dangling connection, but connection will be left hanging until GC doesn’t kick in and this can take a while (if you do not close it explicitly). IF you use "using" (excuse the pun) you will release the connection immediately even if you forgot to close it and even if some exception occured inside the using block.
Another reason, as previous post mentions, is that programmers do not always use finally to clean up. If not using finally in the case of exception you end up with leaking resources…
One situation is when you want to do something at the beginning of a code block, and then undo it at the end of the block, unconditionally (even if there is a throw).
The ctor for the disposable class that you build (and call within the using) would perform the action, and then the Dispose method would undo that action. This is typically how I use it.
Other people has mentioned about "IDisposable" already.
But one of the caveats when using "using" statement is that,
any exceptions thrown within "using" will not be caught
even thought "SomeType" will be disposed regardless.
So in the following snippet,
using (SomeType t = new SomeType()){
throw new Exception("thrown within using");
}
throw new Exception("thrown within using"); should not be disregarded.
I would also add that use a using() statement if something implements IDispose and also if that something you want to dispose of holds on to NON-MANAGED resources like database connections and file handles.
If it's a normal object with say a List<T>, where T is like a Customer object that holds names and address, then you don't need to. The garbage collector is smart enough to manage this for you. But the garbage collector WILL NOT return connections to the connection pool or close file handles.

Is a memory leak created if a MemoryStream in .NET is not closed?

I have the following code:
MemoryStream foo(){
MemoryStream ms = new MemoryStream();
// write stuff to ms
return ms;
}
void bar(){
MemoryStream ms2 = foo();
// do stuff with ms2
return;
}
Is there any chance that the MemoryStream that I've allocated will somehow fail to be disposed of later?
I've got a peer review insisting that I manually close this, and I can't find the information to tell if he has a valid point or not.
You won't leak anything - at least in the current implementation.
Calling Dispose won't clean up the memory used by MemoryStream any faster. It will stop your stream from being viable for Read/Write calls after the call, which may or may not be useful to you.
If you're absolutely sure that you never want to move from a MemoryStream to another kind of stream, it's not going to do you any harm to not call Dispose. However, it's generally good practice partly because if you ever do change to use a different Stream, you don't want to get bitten by a hard-to-find bug because you chose the easy way out early on. (On the other hand, there's the YAGNI argument...)
The other reason to do it anyway is that a new implementation may introduce resources which would be freed on Dispose.
If something is Disposable, you should always Dispose it. You should be using a using statement in your bar() method to make sure ms2 gets Disposed.
It will eventually get cleaned up by the garbage collector, but it is always good practice to call Dispose. If you run FxCop on your code, it would flag it as a warning.
Yes there's a leak, depending on how you define LEAK and how much LATER you mean...
If by leak you mean "the memory remains allocated, unavailable for use, even though you're done using it" and by latter you mean anytime after calling dispose, then then yes there may be a leak, although its not permanent (i.e. for the life of your applications runtime).
To free the managed memory used by the MemoryStream, you need to unreference it, by nullifying your reference to it, so it becomes eligible for garbage collection right away. If you fail to do this, then you create a temporary leak from the time you're done using it, until your reference goes out of scope, because in the meantime the memory will not be available for allocation.
The benefit of the using statement (over simply calling dispose) is that you can DECLARE your reference in the using statement. When the using statement finishes, not only is dispose called, but your reference goes out of scope, effectively nullifying the reference and making your object eligible for garbage collection immediately without requiring you to remember to write the "reference=null" code.
While failing to unreference something right away is not a classical "permanent" memory leak, it definitely has the same effect. For example, if you keep your reference to the MemoryStream (even after calling dispose), and a little further down in your method you try to allocate more memory... the memory in use by your still-referenced memory stream will not be available to you until you nullify the reference or it goes out of scope, even though you called dispose and are done using it.
Calling .Dispose() (or wrapping with Using) is not required.
The reason you call .Dispose() is to release the resource as soon as possible.
Think in terms of, say, the Stack Overflow server, where we have a limited set of memory and thousands of requests coming in. We don't want to wait around for scheduled garbage collection, we want to release that memory ASAP so it's available for new incoming requests.
This is already answered, but I'll just add that the good old-fashioned principle of information hiding means you may at some future point want to refactor:
MemoryStream foo()
{
MemoryStream ms = new MemoryStream();
// write stuff to ms
return ms;
}
to:
Stream foo()
{
...
}
This emphasizes that callers should not care what kind of Stream is being returned, and makes it possible to change the internal implementation (e.g. when mocking for unit testing).
You then will need be in trouble if you haven't used Dispose in your bar implementation:
void bar()
{
using (Stream s = foo())
{
// do stuff with s
return;
}
}
All streams implement IDisposable. Wrap your Memory stream in a using statement and you'll be fine and dandy. The using block will ensure your stream is closed and disposed no matter what.
wherever you call Foo you can do using(MemoryStream ms = foo()) and i think you should still be ok.
I would recommend wrapping the MemoryStream in bar() in a using statement mainly for consistency:
Right now MemoryStream does not free memory on .Dispose(), but it is possible that at some point in the future it might, or you (or someone else at your company) might replace it with your own custom MemoryStream that does, etc.
It helps to establish a pattern in your project to ensure all Streams get disposed -- the line is more firmly drawn by saying "all Streams must be disposed" instead of "some Streams must be disposed, but certain ones don't have to"...
If you ever change the code to allow for returning other types of Streams, you'll need to change it to dispose anyway.
Another thing I usually do in cases like foo() when creating and returning an IDisposable is to ensure that any failure between constructing the object and the return is caught by an exception, disposes the object, and rethrows the exception:
MemoryStream x = new MemoryStream();
try
{
// ... other code goes here ...
return x;
}
catch
{
// "other code" failed, dispose the stream before throwing out the Exception
x.Dispose();
throw;
}
You won't leak memory, but your code reviewer is correct to indicate you should close your stream. It's polite to do so.
The only situation in which you might leak memory is when you accidentally leave a reference to the stream and never close it. You still aren't really leaking memory, but you are needlessly extending the amount of time that you claim to be using it.
If an object implements IDisposable, you must call the .Dispose method when you're done.
In some objects, Dispose means the same as Close and vice versa, in that case, either is good.
Now, for your particular question, no, you will not leak memory.
I'm no .net expert, but perhaps the problem here is resources, namely the file handle, and not memory. I guess the garbage collector will eventually free the stream, and close the handle, but I think it would always be best practice to close it explicitly, to make sure you flush out the contents to disk.
Disposal of unmanaged resources is non-deterministic in garbage collected languages. Even if you call Dispose explicitly, you have absolutely no control over when the backing memory is actually freed. Dispose is implicitly called when an object goes out of scope, whether it be by exiting a using statement, or popping up the callstack from a subordinate method. This all being said, sometimes the object may actually be a wrapper for a managed resource (e.g. file). This is why it's good practice to explicitly close in finally statements or to use the using statement.
Cheers
MemorySteram is nothing but array of byte, which is managed object.
Forget to dispose or close this has no side effect other than over head of finalization.
Just check constuctor or flush method of MemoryStream in reflector and it will be clear why you don't need to worry about closing or disposing it other than just for matter of following good practice.

Difference between 'using' and scoping?

What is the difference between the following two snippets of code:
using (Object o = new Object())
{
// Do something
}
and
{
Object o = new Object();
// Do something
}
I have started using using a lot more but I am curious as to what the actually benefits are as compared to scoping objects.
Edit: Useful tidbits I took from this:
Jon Skeet:
Note that this does not force garbage collection in any way, shape or form. Garbage collection and prompt resource clean-up are somewhat orthogonal.
Will Eddins comment:
Unless your class implements the IDisposable interface, and has a Dispose() function, you don't use using.
The first snippet calls Dispose at the end of the block - you can only do it with types which implement IDisposable, and it basically calls Dispose in a finally block, so you can use it with types which need resources cleaning up, e.g.
using (TextReader reader = File.OpenText("test.txt"))
{
// Use reader to read the file
}
// reader will be disposed, so file handle released
Note that this does not force garbage collection in any way, shape or form. Garbage collection and prompt resource clean-up are somewhat orthogonal.
Basically, you should use a using statement for pretty much anything which implements IDisposable and which your code block is going to take responsibility for (in terms of cleanup).
At the end of using the object gets disposed (the object you put inside the parenthesis has to implement IDisposable). The object gets disposed also in exception cases. And you do not have to wait for the GC to do it at some time (you control it).
EDIT: The disadvantage of the scoping are:
you do not control the disposition of the object
even if you would call dispose at the end of your scope, it would not be exception safe
Just to literally show the difference...
using (FileStream fileStream = new FileStream("log.txt", FileMode.OpenCreate))
{
//stuff with file stream
}
is the same as...
{
FileStream fileStream = new FileStream("log.txt", FileMode.OpenCreate);
try
{
//stuff with filestream
}
finally
{
if (fileStream != null)
((IDisposable)fileStream).Dispose();
}
}
where as
{
FileStream fileStream = new FileStream("log.txt", FileMode.OpenCreate);
fileStream.Dispose();
}
is as it is.
See the documentation regarding IDisposable and determinable resource deallocation.
Simply put, at the end of the using{} block, you can reliably dispose of allocated resources (e.g. close file handles, database connections etc.)
using just requires an implementation of the IDisposable interface, and calls the Dispose method at the end of the scope.
For plenty of raging arguments about properly disposing objects, there's plenty of other threads.

Categories