当连接超时时,TransactionScope会锁定表

时间:2017-03-15 22:34:09

标签: c# .net transactionscope sql-server-2016

我们的WebAPI项目中有一个transactioncope,它执行2个操作 - Operation1&操作2。当因为表锁定而超时时,我们还有一个重试选项。在其中一个场景中,一个db调用operation2超时并且如果第二次尝试成功,则执行的两个操作都不会被提交或回滚。表在数据库中处于锁定状态。下面是代码结构,

//TransactionScope in Main method
TransactionScope scope= new TransactionScope()
{
 Operation1();
 Operation2();
 scope.commit();
}

//First operation method
public void Operation1()
{
 sqlconnection conn= new sqlConnection(connectionstring);
 try
 {
  conn.open();
  cmd = new sqlcommand(conn);
  //Executes successfully
  cmd.executenonquery();
 }
 finally
 {
  conn.close();
 }
}

//Second operation method
public void Operation2()
{
 //Assume that the first time db call in forloop failed because of timeout
 //and the second time call succeeded
 for(int I=0;i<2;i++)
  {
   sqlconnection conn= new sqlConnection(connectionstring);
   try
   {
    conn.open();
    cmd = new sqlcommand(conn);
    cmd.executenonquery();
   }
   catch(Exception e)
   {
     if(e.Message != "Connection Timeout")
     {
       Throw e;
     }
   }
   finally
   {
    conn.close();
   }
  }
}

在这种情况下,当Opearion1成功并且Opeartion2成功进行第二次for循环调用时,两个事务都没有得到提交或回滚。如果在transactionscope代码中发生任何SQL错误或超时,那么transactioncope会被放弃吗?

0 个答案:

没有答案