I have the following code block;
using (var msResp = new MemoryStream(Resp))
{
try
{
Response resp = new Response(msResp);
SetClientIdentityResponseValue sirv = new SetClientIdentityResponseValue(resp, (int)Response.Properties.Value);
if (!sirv.IsCredentialsValid)
{
throw new Exception("Authentication failed.");
}
if (sirv.IsSubscriptionExpired)
{
throw new Exception("Subscription expired.");
}
}
finally
{
msResp.Close();
}
}
I have read somewhere that a using statement automatically disposes the object.
Question:
Is using the Try/Finally combination redundant, when I already use the using statement?
Yes, it is redundant.
The using statement ensures that Dispose is called even if an
exception occurs while you are calling methods on the object. You can
achieve the same result by putting the object inside a try block and
then calling Dispose in a finally block; in fact, this is how the
using statement is translated by the compiler.
using Statement (C# Reference)
You don't need the finally. In fact, the using block is implemented internally using a try... finally.
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.
http://msdn.microsoft.com/en-us/library/yh598w02.aspx
Its redundant. But remember, if you want to catch exception then you need a try-catch. using statement won't catch any exceptions. It just close and disposes the object.
Since you're calling Close rather than Dispose It's not blatantly obvious that the code is redundant.
The documentation for MemoryStream.Dispose indicates that the stream is closed when calling Dispose:
This method disposes the stream, by writing any changes to the backing store and closing the stream to release resources.
Which infers that Close is called. However, there's no harm in explicitly Closing the stream when you're done with it.
Bottom line: Is it redundant? Probably. Is it hurting anthing? Absolutely not. I'd prefer to be in the habit of cleaning up after myself, even if a janitor comes in behind me and has nothing to do (or cleans again).
Related
I am the third generation to work on a system within my organization and of course there are differences in programming styles. I was wondering what the correct way of connecting to a database is as there are two different styles being used within the system. So whats the "correct" way?
Method 1:
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("StoredProcedure", con))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("foo", bar));
}
using (SqlDataReader reader = command.ExecuteReader())
{
//do stuff
}
}
}
catch (Exception ex)
{
//do stuff
}
Method 2:
// Variables
SqlCommand loComm;
SqlConnection loConn = null;
SqlDataReader loDR;
try
{
// Init command
loComm = new SqlCommand("foo");
loComm.CommandType = CommandType.StoredProcedure;
loComm.Parameters.AddWithValue("foo", bar);
// Init conn
loConn = new SqlConnection(String);
loConn.Open();
loComm.Connection = loConn;
// Run command
loDR = loComm.ExecuteReader();
//do stuff
}
catch (Exception ex)
{
//do stuff
}
While both methods work I am not sure which one is the most appropriate to use. Is there a reason to use one over the other? The second method is cleaner and easier to understand to me, but it doesn't automatically run the iDispose() function when it is finished.
Edit: My question is different then the one suggested, because one approach uses the "using" statement while the other doesn't. So my question is directly related to whether or not to utilize the "using" statements when making a database connection.
Thanks, for all the responses.
Method 2 is simply incorrect and should be repaired.
When completed, you will be left with IDisposable instances that have not been disposed. Most likely, this will play havoc with the connection management that goes on behind the scenes with SqlConnection, especially if this code gets thrashed a lot before GC decides to step in.
If an instance is IDisposable, then it needs to be Disposed of, preferably in the smallest scope possible. Using using will ensure that this happens, even if the code malfunctions and exceptions are thrown.
A using statement:
using(var disposableInstance = new SomeDisposableClass())
{
//use your disposable instance
}
is (give or take a few minor details) syntactic sugar for:
var disposableInstance = new SomeDisposableClass();
try
{
//use your disposable instance
}
finally
{
//this will definitely run, even if there are exceptions in the try block
disposableInstance.Dispose();
}
Even if something goes wrong in the try block, you can be assured that the finally block will execute, thereby ensuring that your disposables are disposed, no matter what happens.
In the first example, if there is an exception thrown, the objects wrapped in the using blocks will be properly closed and disposed.
In the second, you will manually need to dispose of your objects.
One other thing worth mentioning is that if you were planning on disposing of your objects only when an exception is thrown, you will have objects that are not disposed of, so you would need to implement a try..catch..finally and dispose the objects within the finally block.
The first is the better option.
The first one will close the connection if an exception is thrown.
The second one won't, so I'd say go with the first choice.
What the using block does is to warranty that the object Dispose method will always be invoked, no matter if an exception is thrown or not.
Dispose is a method used to clean up resources. In the case of a DB connection, the connection is released, which is really important.
So, the correct way in this case is using the using pattern.
The object included between the using parents mus be IDisposable whic means that it has a Dispose method that should be invoked when the object is no longer needed. If you don't invoke dispose, it will be disposde at any indeterminate time, when the garbage collector destroys the object. That's undesirable in case like a DB connection that must be closed as soon as possible.
The equivalen of usin is a try finally, which includes a call to Dispose within the finally block.
Reading here, it says:
As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned. The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.
That sounds like the correct way is method 1.
This question already has answers here:
What is the C# Using block and why should I use it? [duplicate]
(9 answers)
Closed 9 years ago.
I was wondering if it necessary to call Close() in the following situation (if not necessary, why?)
using (var file = System.IO.File.OpenText(myFilePath))
{
...
}
I presume it is necessary in the following situation
StreamWriter file2 = new System.IO.StreamWriter(myFilePath);
newFileContents.ForEach(file2.WriteLine);
file2.Close();
Is it correct?
Edit:
I thought my question is close() - specific, might have been the difference between reading and writing....
With the using construct you get IDisposable.Dispose called automatically at the end of the code block which will close the file. If you don't use the using statement you have to call Close yourself.
With using you also automatically get built-in try/finally exception handling which will behave more gracefully if something goes wrong before you exit your using block. That's another reason using using is a good idea instead of rolling your own.
In your case the using construct is shorthand for:
StreamWriter file2 = new System.IO.StreamWriter(myFilePath);
try
{
newFileContents.ForEach(file2.WriteLine);
}
finally
{
if (file2!= null)
((IDisposable)file2).Dispose();
}
If you decompile StreamWriter's implementation of Dispose you will see this call (among others):
this.stream.Close();
in the finally block (If you need absolute proof ;-)
OpenText returns a StreamReader, which inherits TextReader, which inherits the IDisposable interface, which specifies a Dispose() method.
When the using statement goes out of scope, it calls the Dispose() method on the StreamReader's implementation of Dispose(), which in turn closes the stream (i.e. the underlying file) The whole thing is wrapped in a try/finally block under the covers, which guarantees that Dispose() will always be called.
the using structure calls the object's Dispose method when it reaches the end of the script block. This method closes the file.
Any time you work with a file, you need to make sure to call Dispose or Close in order to let Windows know that the file is free for editing.
Correct.
If wrapped in using clause, a file.Close() is not required
If not wrapped, you are responsible for Close() and Dispose()
I was wondering if it necessary to call Close() in the following situation (if not necessary, why?)
No because the using statement disposes of the object - and thus removes unmanaged resources.
I presume it is necessary in the following situation
Yes, here it would be required so that the unmanaged resources were cleaned up.
It's not necessary because Dispose() will close the underlying file. However since that's an implementation detail it's good practice to explicitly call Close() when you're done with the stream.
If I have the following, will IDisposeable still be called on DisposeableObject, or will the object remain opened because an un-handled exception is encountered?
using ( DisposeableObject = new Object() )
{
throw new Exception("test");
}
A using is like wrapping your code in a try...finally and disposing in the finally, so yes, it should be called.
using expands to a try..finally block, so yes, it will call Dispose.
In the example you provided Dispose will be called before the exception is thrown.
The normal code for ensuring that dispose gets called looks like
var connection= new SqlConnection(connectionString);
try
{
// do something with the connection here
}
finally
{
connection.Dispose();
}
The usings statement replaces the need to write such a cumbersome statement.
using(var connection = new SqlConnection(connectionString))
{
// do something with the connection here
}
According to MSDN, yes. When control leaves the scope of the using statement, expect it to be disposed.
The object will be disposed as you will come out of scope when the exception bubbles up.
See: using Statement (C# Reference)
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.
I am use using to guarantee the resource cleanup. This is fine for the simple block of code.
If I have a method which I need to pass the variable inside the using, can I still guarantee resource clean up?
for example,
using ( FileStream fs = -----)
{
SomeMethod(fs);
}
Yes. using(){} is syntactic sugar, and it will expand your code to this:
FileStream fs = -----;
try {
SomeMethod(fs);
} finally {
if (fs != null)
((IDisposable)fs).Dispose();
}
finally blocks are guaranteed to execute whether an exception is thrown or not. The only time they wouldn't be executed is in the case of a severe runtime failure, such as a stack overflow, out of memory exception, or a crash in the runtime itself.
fs's Dispose() method will be invoked at the end of using's code block.
Yes, it will be disposed.
See the examples on the using Statement on MSDN - the Font is created with passed in parameters.
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.