I have the following code (simplified) to access my database. I know about using statements and parameters but I shortend this to focus my problem.
string ConnectionString = "ConnectionStringHere"; //1. insert Transaction SqlConnection myConnection = new SqlConnection(ConnectionString); SqlTransaction myTrans = myConnection.BeginTransaction(); string sUpdate = "INSERT INTO User (FirstName, LastName) VALUES ('jon','doe')"; SqlCommand myCommand = new SqlCommand(sUpdate, myConnection, myTrans); myCommand.ExecuteNonQuery(); //2. select from the same table SqlConnection myConnection2 = new SqlConnection(ConnectionString); string sSelect = "SELECT FirstName, LastName FROM User WHERE ID = 123"; DataTable dtResult = new DataTable(); SqlDataAdapter myDataAdapter2 = new SqlDataAdapter(sSelect, myConnection2); myDataAdapter2.Fill(dtResult); //TimeOut Exception here //submit changes from my transaction here myTrans.Commit(); In the second part I get a TimeOutExcetion because I can't access my User table until I commit my transaction myTrans.Commit(); which is after that - deadlock.
My question here is - what's the best practice to avoid deadlocks here? I could avoid the Exception by making the SELECT part of the transaction or by setting the IsolationLevel
SqlTransaction myTrans = myConnection.BeginTransaction(IsolationLevel.ReadUncommitted); But I'm not sure about the usage of those. I don't have to worry about invalid data because I always select by ID.
using-statement