please consider this code :
1-...
2-{
3-...
4-SqlConnection cn=new SqlConnection();
5-...
6-}
if program reach to statement No.6 will cn
dispose? if not what happend for cn
variable?
please consider this code :
1-...
2-{
3-...
4-SqlConnection cn=new SqlConnection();
5-...
6-}
if program reach to statement No.6 will cn
dispose? if not what happend for cn
variable?
if program reach to statement No.6 will cn dispose?
No.
if not what happend for cn variable?
It depends whether you use it afterwards. If you don't use it and it falls out of scope which means that it is eligible for garbage collections. When this garbage collection happens is out of your control. But when it happens the destructor will be invoked which itself calls the Dispose
method.
This being said the correct approach is to always wrap IDisposable
resources in using
statements. This ensures that the Dispose method will always be called, even if an exception is thrown:
2-{
3-...
4-using (SqlConnection cn=new SqlConnection())
{
...
}
5-...
6-}
No, it will be disposed when GarbageCollector decides to destroy it.
If you want to dispose it then use using
statement (as SqlConnection
implements IDisposeable
):
using(SqlConnection cn = new SqlConnection())
{
// code
}
No, the object will not be disposed when the variable goes out of scope.
When the object is not used any more (which is somewhere inside the scope, after the last line that uses the variable), the object is up for garbage collection.
The next time the garbage collector runs, it will find that the object is not used any more, but it will also find that it has a Finalize
method, and that it's not disposed, so the object will be added to the finaliser queue. Also, as the object is not collected, it will likely be moved to the next heap generation, which involves actually moving the object from one place in memory to another.
The garbage collector has a special thread that finalises objects from the finaliser queue, which will eventually finalise the object. The Finalize
method of the object will call the Dispose
method, which closes the database connection.
After the object has been disposed, it will eventually be collected by the garbage collector.
Note that there is no gurantee that the object will be finalised within any specific time, or even finalised at all.
So, if you don't dispose the connection object, the two main things that happen is:
You should use a Using statement, but the result will be the same it wont be disposed it will be marked as disposable and the GC will collect it the next time it runs.
No Kerezo,
1-...
2-{
3-...
4-SqlConnection cn=new SqlConnection();
5-...
6-}
We the compiler reaches the Statement cn object is not destroyed.You can't access the "cn" object out of the loop.
If you use the Using block then the object will be disposed automatically.