String constr = ConfigurationManager. ConnectionStrings ["myCon"]. ConnectionString;
String constr2 = ConfigurationManager. ConnectionStrings ["myCon2"]. ConnectionString;
String SQL = "insert into [Tuser] (username, pwd, age) values ('committabletransaction', 'bbb', 10 )";
String sq2 = "insert into [Tuser] (username, pwd, age) values ('committabletransaction', 'bbb ', 'ssssss ')";
# Region CommittableTransaction distributed
Using (SqlConnection con = new SqlConnection (constr), con2 = new SqlConnection (constr2 ))
{
Con. Open ();
Con2.Open ();
CommittableTransaction ct = new CommittableTransaction (); // CommittableTransaction is created after the connection is opened
// The transaction performance is not good.
Con. EnlistTransaction (ct); // register distributed transactions in CommittableTransaction
Con2.EnlistTransaction (ct );
Try
{
Using (SqlCommand cmd = new SqlCommand (SQL, con ))
{
Int a = cmd. ExecuteNonQuery ();
Console. WriteLine ();
}
Using (SqlCommand cmd = new SqlCommand (sq2, con2 ))
{
Int B = cmd. ExecuteNonQuery ();
Console. WriteLine (B );
}
Ct. Commit (); // submit the transaction
}
Catch (Exception ess)
{
Console. WriteLine (ess. Message );
Ct. Rollback (); // roll back the transaction
}
// The connection is used elsewhere. Distributed transactions must be cleared.
Con. EnlistTransaction (null );
Con2.EnlistTransaction (null );
}
# Endregion
Although distributed transactions are implemented. However, the performance is really poor. Therefore, distributed transactions are not required. It is best not to use it. Especially when multiple transactions are concurrently executed.