commiting Transaction and underlauing connection

  • Thread starter Thread starter Shimon Sim
  • Start date Start date
S

Shimon Sim

Hi I have following code

public void Functon1()
{
SqlTransaction trans=CreateTransaction();
//Do something with it

trans.Commit();

}

private SqlTransaction CreateTransaction()
{
SqlConnection con=new SqlConnection("some connection string");
return con.BeginTransaction();
}

I just wanted to know what will happen with my Connection. Will it be still
open or not?
trans.Connection property is always null after I commit the transaction.
Does it mean anything?
Thanks, Shimon.
 
Hi,

It depends on a scope of the connection. Actual connection still should be
opened, but in your case connection is local to the function, which means as
soon as you commit transaction, then connection should be destroyed
 
Thanks,
so I can safely assume that it will be closed, since it is just a local
variable?
Shimon.
 
Shimon Sim said:
Thanks,
so I can safely assume that it will be closed, since it is just a local
variable?
Shimon.

No. Your code is not correct. It leaks connections and will cause your
application to fail.

Commiting the transaction will cause the Connection to fly away into the
unreachable spaces of the managed heap where it will remain open until it is
garbage collected and finalized. Which may be a very long time.

David
 
Thank you for your comment.
I guess I will have to drop the notion of creating SqlConnection as local
variable to open a Transaction object with bigger scope.

Shimon.
 
Back
Top