2011-05-05 70 views
5

我已經構建了一個類來同步兩個不同數據源之間的數據。這種同步分爲多個部分(和方法)。每種方法都有自己的TransactionScope,並且方法按順序運行。ASP.NET中TransactionScope的問題

每次我運行此代碼我碰到下面的ErrorMessage:

「與當前連接關聯的事務已完成但尚未配置之前,連接可用於執行SQL的事務必須配置。聲明「。

下面的代碼是與一個TransactionScope這樣的方法的一個示例:

private void SomeMethod() 
{ 
     try 
     { 
      using (var _transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions)) 
      { 
       using (SqlConnection _connection = new SqlConnection(connectionstring)) 
       { 
        _connection.Open(); 

        DoSomething()... 
       } 

       _transactionScope.Complete(); 
      } 
     } 
     catch (TransactionAbortedException e) 
     { 
      nlog.Error(string.Format("The transaction has been aborted: {0}", e.Message)); 
      throw e; 
     } 
     catch (Exception e) 
     { 
      throw e; 
     } 
} 

看來,呼叫「_transactionScope.Complete()」不足以殺死的TransactionScope ..有沒有人有線索我做錯了什麼?

在此先感謝!

UPDATE 感謝您的回覆。經過幾次測試後,我發現只有在一種方法中有多個查詢時纔會出現此問題。例如:

try 
    { 
     using (TransactionScope _transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions)) 
     { 
      using (SqlConnection _connection = new SqlConnection(connectionstring)) 
      { 
       _connection.Open(); 

       //new method: 
       using (TransactionScope _transactionScope = new TransactionScope(TransactionScopeOption.Suppress)) 
       { 
        //a selectquery 
       } 

       //an update or insert query 

      _transactionScope.Complete(); 
     } 
    } 
+1

如果交易的運行可能會出現此錯誤比maxTimeout更長的時間段。看到這篇博文:http://thecodesaysitall.blogspot.se/2012/04/long-running-systemtransactions.html或這個答案:http://stackoverflow.com/a/10017056/205023 – Marcus 2012-04-04 18:24:22

+1

是你的交易持續超過10分鐘? – 2011-05-07 01:08:23

+0

有一些交易我認爲持續10分鐘以上,但我通過設置'transactionOptions.Timeout'屬性和de SqlCommand.CommandTimeout屬性爲1小時來處理。 – user740229 2011-05-07 09:51:53

回答

5

嘗試更改構造函數。

using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, 
       new TransactionOptions() 
       { 
        IsolationLevel = System.Transactions.IsolationLevel.Serializable, 
        Timeout = TimeSpan.FromSeconds(120) 
       })) 
3

我做了一個交易範圍

public static TransactionScope CreateDefaultTransactionScope(TransactionScopeOption option = TransactionScopeOption.Required) 
    { 
     var transactionOptions = new TransactionOptions(); 
     transactionOptions.Timeout = TimeSpan.MaxValue; 
     transactionOptions.IsolationLevel = IsolationLevel.ReadCommitted; 
     return new TransactionScope(option, transactionOptions); 
    } 

創造最大的超時值,然後你會使用它的方法:

using (TransactionScope transaction = TransactionHelper.CreateDefaultTransactionScope()) 
+0

查看此鏈接以及:http://social.msdn.microsoft.com/forums/en-US/windowstransactionsprogramming/thread/250b40b9-0838-4142-a8ff-d9d26690083b/ – 2011-05-06 16:42:07