I've the following code
using(MemoryStream ms = new MemoryStream())
{
//code
return 0;
}
The dispose() method is called at the end of using statement braces } right? Since I return before the end of the using statement, will the MemoryStream object be disposed properly? What happens here?
Yes, Dispose will be called. It's called as soon as the execution leaves the scope of the using block, regardless of what means it took to leave the block, be it the end of execution of the block, a return statement, or an exception.
As #Noldorin correctly points out, using a using block in code gets compiled into try/finally, with Dispose being called in the finally block. For example the following code:
using(MemoryStream ms = new MemoryStream())
{
//code
return 0;
}
effectively becomes:
MemoryStream ms = new MemoryStream();
try
{
// code
return 0;
}
finally
{
ms.Dispose();
}
So, because finally is guaranteed to execute after the try block has finished execution, regardless of its execution path, Dispose is guaranteed to be called, no matter what.
For more information, see this MSDN article.
Addendum:
Just a little caveat to add: because Dispose is guaranteed to be called, it's almost always a good idea to ensure that Dispose never throws an exception when you implement IDisposable. Unfortunately, there are some classes in the core library that do throw in certain circumstances when Dispose is called -- I'm looking at you, WCF Service Reference / Client Proxy! -- and when that happens it can be very difficult to track down the original exception if Dispose was called during an exception stack unwind, since the original exception gets swallowed in favor of the new exception generated by the Dispose call. It can be maddeningly frustrating. Or is that frustratingly maddening? One of the two. Maybe both.
using statements behave exactly like try ... finally blocks, so will always execute on any code exit paths. However, I believe they are subject to the very few and rare situations in which finally blocks are not called. One example that I can remember is if the foreground thread exits while background threads are active: all threads apart from the GC are paused, meaning finally blocks are not run.
Obvious edit: they behave the same apart from the logic that lets them handle IDisposable objects, d'oh.
Bonus content: they can be stacked (where types differ):
using (SqlConnection conn = new SqlConnection("string"))
using (SqlCommand comm = new SqlCommand("", conn))
{
}
And also comma-delimited (where types are the same):
using (SqlCommand comm = new SqlCommand("", conn),
comm2 = new SqlCommand("", conn))
{
}
Your MemoryStream object will be disposed properly, no need to worry about that.
With the using statement, the object will be disposed of regardless of the completion path.
Further reading...
http://aspadvice.com/blogs/name/archive/2008/05/22/Return-Within-a-C_2300_-Using-Statement.aspx
http://csharpfeeds.com/post/8451/Return_Within_a_Csharp_Using_Statement.aspx
Take a look at your code in reflector after you compile it. You'll find that the compiler refactors the code to ensure that dispose is called on the stream.
Related
While retriving data for mutiple AJAX call with 2 different methods using DataReader.
method 1:
using (SqlDataReader reader = clientDb.ExecuteSPReader("SP1",
CommandBehavior.CloseConnection,
parameters))
{
if (reader.HasRows)
{
while (reader.Read())
{
}
reader.Close();
}
}
method 2:
using (SqlDataReader reader = clientDb.ExecuteSPReader("SP2",
CommandBehavior.CloseConnection,
parameters))
{
if (reader.HasRows)
{
while (reader.Read())
{
}
reader.Close();
}
}
both the method is execute on a single db. Should it suggested that I would not close the reader, as It will be closed by GC? and I am executing reader with "using" statement.
In my case, issue is as both the method is using same database. One method
reader.close()
closes the other method connection and it jumps to exception. So, wanted to know what is the best way to implement such a AJAX request methods.
I have also read in following url that one should not close or dispose the managed objects.
https://msdn.microsoft.com/en-us/library/8xx3tyca%28v=vs.110%29.aspx
First, by using the using statement, when the execution leaves the scope, SqlDataReader will be disposed. It is the same as calling reader.Dispose() manually.
Since the reader don't have a dependency on external or un-managed code, like your SqlConnection, you don't have to dispose it but you should always close it. The disposal will be managed by the GC.
Further on you should really wrap your SqlConnection in a using statement, since it's using a connection pool to the database. And it is not very good for performance if you leave a lot of open connections to the database, when they are not in use.
I assume these database calls are made in two different calls to the server, and not in sequence just after each other in the same method.
I have this specific situation where I need to execute a stored procedure 3 times before I declare it failed. Why 3 times because to check if a job that was started earlier finished. I am going to ask a separate question for deciding if there is a better approach. But for now here is what I am doing.
mysqlparametersArray
do{
reader = MyStaticExecuteReader(query,mysqlparametersArray)
Read()
if(field(1)==true){
return field(2);
}
else{
//wait 1 sec
}
}while(field(1)==false);
MyStaticExecuteReader(query,mysqlparametersArray)
{
//declare command
//loop through mysqlparametersArray and add it to command
//ExecuteReader
return reader
}
Now this occasionally gave me this error:
The SqlParameter is already contained by another
SqlParameterCollection.
After doing some search I got this workaround to Clear the parameters collection so I did this:
MyStaticExecuteReader(query,mysqlparametersArray)
{
//declare command
//loop through mysqlparametersArray and add it to command Parameters Collection
//ExecuteReader
command.Parameters.Clear()
return reader
}
Now I am not getting that error.
Question: Is there any side-effect using .Clear() method above?
Note: Above is a sample pseudo code. I actually execute reader and create parameters collection in a separate method in DAL class which is used by others too. So I am not sure if making a check if parameters collection is empty or not before adding any parameters is a good way to go.
I have not ran into any side effects when I have used this method.
Aside from overhead or possibly breaking other code that is shared, there is no issue with clearing parameters.
I'm fairly new to BizTalk and creating a custom pipeline component. I have seen code in examples that are similar to the following:
public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg)
{
Stream originalDataStream = pInMsg.BodyPart.GetOriginalDataStream();
StreamReader strReader = new StreamReader(originalDataStream);
string strOriginalData = strReader.ReadToEnd();
byte[] bufferOriginalMessage = new byte[strOriginalData.Length];
bufferOriginalMessage = ASCIIEncoding.Default.GetBytes(strOriginalData);
Stream ms = new MemoryStream();
ms.Write(bufferOriginalMessage, 0, strOriginalD
//other stuff here
ms.Seek(0, SeekOrigin.Begin);
pInMsg.BodyPart.Data = ms;
}
But nowhere in the method is the StreamReader being closed or disposed. The method simply exits.
Normally when using StreamReader and other classes, it is best practice to use a using statement so that the stream is automatically disposed.
Is there a particular reason (perhaps in BizTalk) why you wouldn't dispose this StreamReader?
I have not found any information on this point. Can anyone help?
In general, yes, it's a good practice to close readers and streams you don't need anymore. That said, there might not necessarily be 100% required everytime. For example, closing the reader would close the underlying stream normally, but chances are, something else is probably already aware of the stream and will close it at the right time on it's own.
What is good practice, however, is to add any streams you use in a pipeline component with a lifetime matching that of the message to the resource tracker, so that BizTalk can dispose them automatically when the pipeline execution finishes and the message has been processed.
in ASP.NET, I have seen people coding like this
using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString))
{
// Do the datatbase transactions
}
How does it differ from this one
SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString)
// Do the datatbase transactions
Is there any performance/speed improvements in using one over the other ?
The using statement allows the
programmer to specify when objects
that use resources should release
them. The object provided to the using
statement must implement the
IDisposable interface. This interface
provides the Dispose method, which
should release the object's resources.
A using statement can be exited either
when the end of the using statement is
reached or if an exception is thrown
and control leaves the statement block
before the end of the statement.
A good article can be found here
Understanding the 'using' statement in C#
It's just a shortcut. :)
using (var foo = new Foo())
foo.bar();
equals to:
Foo foo = new Foo();
try
{
foo.bar();
}
finally
{
if (foo != null)
((IDisposable)foo).Dispose();
}
using keyword ensures that object will be disposed (it must implement IDisposable).
It's useful when working with external resources (database connection, file streams etc.) - they will be released despite of errors that may occur.
Using: Defines a scope, outside of which an object or objects will be disposed.
So its just syntax instead of creating the object then disposing it.
More details on MSDN
objects created in the using construct have lifetime within the construct (the braces {}). And if you notice only those members which implement the IDisposable interface can only be created. It simply means that right after the using construct code the the compiler will automatically call the dispose method on the object you've created. It helps in garbage collection.
As in the case of SqlConnection objects we must call dispose otherwise the ado.net connection pool (which manages connections to database) will assign a new connection to another incoming request instead of reusing an old connection pool. Connection pooling is simply an inherent way to minimize the resources & time taken to acquire a connection to a database.
Refer:
Connection Pooling
IDisposable
using statement is a shortcut for
try
{
/* do the work here with obj */
}
finally
{
if (obj != null)
obj.Dispose();
}
In general, you should use the using syntax for any object that implements IDisposable - for example, SqlConnection.
The using statement ensures that the object is disposed correctly at the end of the block in (almost) all circumstances, even if exceptions occur.
There aren't any direct speed/performance differences either way, but if you don't dispose of your IDisposable objects (usually by using using) then you might encounter problems down the line because vital resources haven't been tidied up.
Using using is good practice and almost always the right way to do things. Not using using is usually a bad idea, unless you're absolutely certain of what you're doing and why.
the using statement would automatically call the finally, i.e once the using block is finished, it will dispose off the object.
using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString))
{
// Do the datatbase transactions
}
is equivalent to:
SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString)
// Do the datatbase transactions
myConnection.Close();
myConnection.Dispose()
If I use something like:
using (OdbcConnection conn = new OdbcConnection(....))
{
conn.open();
my commands and sql, etc.
}
Do I have to do a conn.close(); or does the using statement keep me from doing that last call? Does it dispose of everything in the using block? For example, if I called other objects unlrelated would it dipose of those automatically also?
Thank you. I was unclear after reading about using on Microsoft's site. I want to make sure I don't have any memory leaks.
The using block will dispose of the OdbcConnection.
Normal scope rules work for anything declared inside the using block.
The using block will not clean up any other IDisposable objects. It only cleans up the declared item
note that you can nest using blocks, or if the items are the same type, multiple items can be initialized at the same time.
See the top bit of my other answer for How do I use the using keyword in C# for a little more information.
I should also mention that you can close (dispose) of the connection as soon as you are done with it to release the resource. The guidelines say that the caller should be able to repeatedly call the dispose method. The using block is essentially just a safety net and allows writing clearer code in most circumstances.
[Edit]
e.g. multiple initialization in a using: initialize more than one object in the same using without having to nest using blocks if the objects are the same type:
using (Bitmap b1 = new Bitmap("file1"), b2 = new Bitmap("file2"))
{ ... }
Joel Coehoorn mentioned stacking, which is nesting but omitting the braces, much as you can omit the braces in a for, or if statement. The UI doesn't reformat with an indent. I'd be curious what the IL looks like.
using(Bitmap b = new Bitmap("filex"))
using(Graphics g = Graphics.FromImage(b))
{
}
It is an error to use put different objects in the same using error CS1044: Cannot use more than one type in a for, using, fixed, or declaration statement.
// error CS1044
using(Bitmap b = new Bitmap("filex"), Graphics g = Graphics.FromImage(b))
The using statement will handle calling the Close and Dispose methods for you.
Scott Hanselman has a pretty good explanation of the using statement.
The using statement ensures that an object which implements IDisposable gets disposed. It will only dispose the object that is referened in the using block so your code is basically equivlant to:
OdbcConnection conn = new ....;
try
{
conn.open();
conn.....
}
finally
{
conn.dispose();
}