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.
精彩评论