Handle Exception that happens within a using statement (IDisposable) - c#

I'm using the DataWriter and DataReader interfaces.
These classes have the IDisposable interface implemented, therefore I wrap them around the using keyword:
using(var datareader = new DataReader(SerialPortInputStream))
{
CancellationTokenSource cancellation = new CancellationTokenSource();
//Timeout
cancellation.CancelAfter(1000);
//...
datareader.LoadAsync(120).AsTask(cancellation.Token);
//Some fancy methods
...
//Last step: Detach the InputStream to use it again
datareader.DetachStream();
}
This thread here is saying that if an Exception (here a "TaskCancelledException" happens inside a using statement, the object gets disposed. Now, the problem is with the UWP-DataReader and DataWriter: They will close the underlying stream if the object gets disposed. To prevent that I've to call datareader.DetachStream() and then dispose.
We cannot use the DataReader/DataWriter with a using statement when we need the underlying InputStream/Outputstream later again.
Is this conclusion correct or are there other ways to handle this situation?

The whole meaning of using is to make sure that the object gets disposed at the end of the block no matter what happens without having to write all the code for this by yourself. This is done by disposing the object inside a finally block.
What you are trying to do is to call datareader.DetachStream() before the object gets disposed - again no matter what happens.
So my conclusion would be that the using statement isn't very helpful here and you should do this by yourself, maybe like this:
DataReader datareader = null;
try
{
datareader = new DataReader(SerialPortInputStream);
CancellationTokenSource cancellation = new CancellationTokenSource();
//Timeout
cancellation.CancelAfter(1000);
//...
datareader.LoadAsync(120).AsTask(cancellation.Token);
//Some fancy methods
...
}
finally
{
//Last step: Detach the InputStream to use it again
datareader?.DetachStream();
datareader?.Dispose();
}
So this is essentially what the using statement does to your code, except that you can insert the datareader?.DetachStream() call.
Note that the datareader would eventually get disposed anyway even without the using statement. When the scope of this variable is left, the garbage collection may anytime decide to remove this instance from memory which would lead to a call to its Dispose method. So a call to DetachStream() is needed before leaving the scope.

Related

What is the proper way to close a connection when using ExecuteScalar and EnterpriseLibrary.Data.Database

I haven't found the proper way to close the connection or Dispose when I use Microsoft.Practices.EnterpriseLibrary.Data.Database and the ExecuteScalar method.
I can't use a using block cause object doesn't implement IDisposable. And I haven't figured out how to Dispose if I use a Finally block instead. Do I need to do this, or my first using block will Dispose/Close the connection on the ExecuteScalar ?
This is my code:
DatabaseProviderFactory factory = new DatabaseProviderFactory();
DatabaseFactory.SetDatabaseProviderFactory(factory, false);
Database db = ... ;
// Initialize command
using (DbCommand dbCommand = db.GetStoredProcCommand("XXXXXX"))
{
object r;
// Execute command
using (r = (object)db.ExecuteScalar(dbCommand)) //Getting error here
{
//Other code here
}
}
The second using statement is not required.
Here the object that should be disposed is dbCommand. Not the objects returned from it's methods.
The first using statement takes care of it.
If you do not want to use using at all, (on the dbCommand) then you can dispose with try/finally in finally block.
Below link explains how to do that.
https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects

Will Db conneection get closed in following situaltion?

I have question on connection I create in C# code
To Read data I have written Factory Class for all the read which is as follows
Public static OracleDataReader(CommandType ct,string command,params OracleParameter[] cp)
{
OracleConnection cn = new OracleConnection(getconnection());
try
{
return ExecuteReader(cn,ct,command,cp);
}
catch
{
cn.close();
}
}
Now I use it as follows
qry = "select * from emp";
using(IDataReader dr = OracleFacoty.ExecuteReader(CommandType.Text,qry,null)
{
while(dr.read())
{
//Do operation
}
}
Now my question is, will the connection opened in factory method will be closed automatically or I Need pass the connection from calling method and close the connection once i am done with data read.
The using statement will dispose the dB connection properly when it's instantiated within it checkout this from msdn regarding this approach of like you did
You can instantiate the resource object and then pass the variable to the using statement, but this is not a best practice. In this case, the object remains in scope after control leaves the using block even though it will probably no longer have access to its unmanaged resources. In other words, it will no longer be fully initialized. If you try to use the object outside the using block, you risk causing an exception to be thrown. For this reason, it is generally better to instantiate the object in the using statement and limit its scope to the using block.
I would suggest probably use using and instantiate connection and pass that instance to your factory methods to perform any operations, by end the using will then properly dispose the database connection.
https://msdn.microsoft.com/en-us/library/yh598w02.aspx
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection(v=vs.110).aspx
By looking at your code, I can say
You have a static method in class which Creates new Connection each time you call it and returns some DataTable object(?)
Whenever an error occurs within ExecuteReader(), exception is suppressed and connection closes without questions.
But in Second snippet, you're not using OracleDataReader you're directly calling ExecuteReader() which, as I believe, will not handle any exceptions.
Also, in first snippet, connection closes only when an error occurs. If no error, connection will not close and will cause memory leaks and after some attempts it max outs connection limits.
If you need new connection for every call, then put the Cn.close() in finally{} block.

SQL Connection constructor outside the using statement

I have the following code:
SqlConnection Connect = new SqlConnection(IST_DBConnect.SQLConnectionString);
SqlCommand command = new SqlCommand(sqlCommandString, Connect);
RequestRow Result = new RequestRow();
Connect.Open();
using (Connect)
...
This is not my code, I would write the creation of the SQL Connection in a using statement, this is a code of my friend, I am no exactly sure if this is going to dispose properly the SQL connection object if something goes wrong in the constructor or in the Open method. So my question is if the connection object is created and the open method throws an exception => the connection is never opened, will this be disposed properly?
Thanks.
From documentation;
As a rule, when you use an IDisposable object, you should declare and
instantiate it in a using statement.
and
You can instantiate the resource object and then pass the variable to
the using statement, but this is not a best practice. In this case,
the object remains in scope after control leaves the using block even
though it will probably no longer have access to its unmanaged
resources. In other words, it will no longer be fully initialized. If
you try to use the object outside the using block, you risk causing an
exception to be thrown. For this reason, it is generally better to
instantiate the object in the using statement and limit its scope to
the using block.
Based on your example, if somethings goes wrong in constructor, of Open method, there is nothing using can do since you use it as a resource after you initialize it.
Sure this is the best way;
using(var Connect = new SqlConnection(IST_DBConnect.SQLConnectionString))
using(var command = Connect.CreateCommand())
{
//
} // <-- Both Connect and command will disposed here no matter exception is thrown or not

What happens if i return before the end of using statement? Will the dispose be called?

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.

Using the using statement in C# [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
What is the C# Using block and why should I use it?
I have seen the using statement used in the middle of a codeblock what is the reason for this?
The using syntax can(should) be used as a way of defining a scope for anything that implements IDisposable. The using statement ensures that Dispose is called if an exception occurs.
//the compiler will create a local variable
//which will go out of scope outside this context
using (FileStream fs = new FileStream(file, FileMode.Open))
{
//do stuff
}
Alternatively you could just use:
FileStream fs;
try{
fs = new FileStream();
//do Stuff
}
finally{
if(fs!=null)
fs.Dispose();
}
Extra reading from MSDN
C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.
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.
It is often used when opening a connection to a stream or a database.
It behaves like a try { ... } finally { ... } block. After the using block, the IDisposable object that was instantiated in the parenthesis will be closed properly.
using (Stream stream = new Stream(...))
{
}
With this example, the stream is closed properly after the block.
using is try finally syntaxical suger for anything that has an IDisposable.. like a sqlconnection. Its use it make sure something is disposed after its out of the using(){} scope.
using(SqlConnection conn = new SqlConnection(connString))
{
//use connection
}
//shorter than
SqlConnection conn = new SqlConnection(connString)
try
{
//use connection
}
finally
{
conn.Dispose();
}
The using statement ensures an object is properly disposed once it is nolonger required.
It basically saves you writing obj.Dispose(); and gives a visual guide as to the scope and usage of an variable.
See the MSDN page for more info
This form of using has to do with freeing resources. It can only be used in combination with class that implement the IDisposable interface.
example:
using(SqlConnection conn = new SqlConnection(someConnectionString))
{
//Do some database stuff here
}
at the end of the using block conn.Dispose is called, even if an exception was thrown inside the block. In the case of a SwqlConnection object means that the connection is always closed.
A drawback of this construction is that there is now way of knowing what happend.
Hope this helps answer your question?
Whenever your code creates an object that implements IDisposable, your code should do the creation inside a using block, as seen above.
There is one exception to this rule. An error in the design of WCF proxy classes prevents using statements from being useful for proxy classes. Briefly, the Dispose method on a proxy class may throw an exception. The WCF team saw no reason not to permit this.
Unfortunately, not seeing a reason doesn't mean that there is no reason:
try
{
using (var svc = new ServiceReference.ServiceName())
{
throw new Exception("Testing");
}
}
catch (Exception ex)
{
// What exception is caught here?
}
If the implicit Dispose call throws an exception, then the catch block will catch that exception instead of the one thrown within the using block.

Categories

Resources