8

しばらく前に、予期していなかったときにTransactionScopeがMSDTCにエスカレートすることについて質問しました。(前の質問

要約すると、SQL2005では、TransactionScopeを使用するために、TransactionScopeの存続期間内にインスタンス化して開くことができるのは単一のSqlConnectionのみです。SQL2008では、複数のSqlConnectionsをインスタンス化できますが、一度に開くことができるのは1つだけです。SQL2000は常にDTCにエスカレートします...アプリケーションであるWinFormsアプリではSQL2000をサポートしていません。

単一接続のみの問題に対する私たちの解決策は、LocalTransactionScope(別名「LTS」)と呼ばれるTransactionScopeヘルパークラスを作成することでした。これはTransactionScopeをラップし、最も重要なこととして、アプリケーションの単一のSqlConnectionインスタンスを作成および維持します。幸いなことに、それは機能します。さまざまなコードでLTSを使用でき、それらはすべてアンビエントトランザクションに参加します。非常に素晴らしい。問題は、作成されたすべてのルートLTSインスタンスが接続プールから接続を作成し、効果的に強制終了することです。「効果的にキル」とは、SqlConnetionをインスタンス化することを意味します。これにより、新しい接続(何らかの理由で、プールからの接続を再利用することはありません)。ルートLTSが破棄されると、接続を解放してプールに戻すことになっているSqlConnectionを閉じて破棄し、再利用できるようにします。明らかに再利用されることはありません。プールは最大になるまで膨張し、max-pool-size+1接続が確立されるとアプリケーションは失敗します。

以下に、LTSコードの簡略版と、接続プールの枯渇を示すサンプルコンソールアプリケーションクラスを添付しました。接続プールの肥大化を監視するには、SQL ServerManagmentStudioの「ActivityMonitor」または次のクエリを使用します。

SELECT DB_NAME(dbid) as 'DB Name',
COUNT(dbid) as 'Connections'
FROM sys.sysprocesses WITH (nolock)
WHERE dbid > 0
GROUP BY dbid

ここにLTSを添付します。これを使用して、プールからの接続を消費し、再利用したり解放したりしないことを自分で示すことができるコンソールアプリケーションのサンプルを作成します。LTSをコンパイルするには、System.Transactions.dllへの参照を追加する必要があります。

注意事項:SqlConnectionを開いたり閉じたりするのは、ルートレベルのLTSであり、常にプール内の新しい接続を開きます。ルートLTSインスタンスのみがSqlConnectionを確立するため、LTSインスタンスをネストしても違いはありません。ご覧のとおり、接続文字列は常に同じであるため、接続を再利用する必要があります。

接続が再利用されない原因となる、私たちが満たしていない不可解な条件はありますか?プーリングを完全にオフにする以外に、これに対する解決策はありますか?

public sealed class LocalTransactionScope : IDisposable
{
      private static SqlConnection _Connection;    

      private TransactionScope _TransactionScope;
      private bool _IsNested;    

      public LocalTransactionScope(string connectionString)
      {
         // stripped out a few cases that need to throw an exception
         _TransactionScope = new TransactionScope();

         // we'll use this later in Dispose(...) to determine whether this LTS instance should close the connection.
         _IsNested = (_Connection != null);

         if (_Connection == null)
         {
            _Connection = new SqlConnection(connectionString);

            // This Has Code-Stink.  You want to open your connections as late as possible and hold them open for as little
            // time as possible.  However, in order to use TransactionScope with SQL2005 you can only have a single 
            // connection, and it can only be opened once within the scope of the entire TransactionScope.  If you have
            // more than one SqlConnection, or you open a SqlConnection, close it, and re-open it, it more than once, 
            // the TransactionScope will escalate to the MSDTC.  SQL2008 allows you to have multiple connections within a 
            // single TransactionScope, however you can only have a single one open at any given time. 
            // Lastly, let's not forget about SQL2000.  Using TransactionScope with SQL2000 will immediately and always escalate to DTC.
            // We've dropped support of SQL2000, so that's not a concern we have.
            _Connection.Open();
         }
      }

      /// <summary>'Completes' the <see cref="TransactionScope"/> this <see cref="LocalTransactionScope"/> encapsulates.</summary>
      public void Complete() { _TransactionScope.Complete(); }

      /// <summary>Creates a new <see cref="SqlCommand"/> from the current <see cref="SqlConnection"/> this <see cref="LocalTransactionScope"/> is managing.</summary>
      public SqlCommand CreateCommand() { return _Connection.CreateCommand(); }

      void IDisposable.Dispose() { this.Dispose(); }

      public void Dispose()
      {
          Dispose(true); GC.SuppressFinalize(this);
      }

      private void Dispose(bool disposing)
      {
         if (disposing)
         {
            _TransactionScope.Dispose();
            _TransactionScope = null;    

            if (!_IsNested)
            {
               // last one out closes the door, this would be the root LTS, the first one to be instanced.
               LocalTransactionScope._Connection.Close();
               LocalTransactionScope._Connection.Dispose();    

               LocalTransactionScope._Connection = null;
            }
         }
      }
   }

これは、接続プールの枯渇を示すProgram.csです。

class Program
{
      static void Main(string[] args)
      {
         // fill in your connection string, but don't monkey with any pooling settings, like
         // "Pooling=false;" or the "Max Pool Size" stuff.  Doesn't matter if you use 
         // Doesn't matter if you use Windows or SQL auth, just make sure you set a Data Soure and an Initial Catalog
         string connectionString = "your connection string here";

         List<string> randomTables = new List<string>();
         using (var nonLTSConnection = new SqlConnection(connectionString))
         using (var command = nonLTSConnection.CreateCommand())
         {
             command.CommandType = CommandType.Text;
             command.CommandText = @"SELECT [TABLE_NAME], NEWID() AS [ID]
                                    FROM [INFORMATION_SCHEMA].TABLES]
                                    WHERE [TABLE_SCHEMA] = 'dbo' and [TABLE_TYPE] = 'BASE TABLE'
                                    ORDER BY [ID]";

             nonLTSConnection.Open();
             using (var reader = command.ExecuteReader())
             {
                 while (reader.Read())
                 {
                     string table = (string)reader["TABLE_NAME"];
                     randomTables.Add(table);

                     if (randomTables.Count > 200) { break; } // got more than enough to test.
                 }
             }
             nonLTSConnection.Close();
         }    

         // we're going to assume your database had some tables.
         for (int j = 0; j < 200; j++)
         {
             // At j = 100 you'll see it pause, and you'll shortly get an InvalidOperationException with the text of:
             // "Timeout expired.  The timeout period elapsed prior to obtaining a connection from the pool.  
             // This may have occurred because all pooled connections were in use and max pool size was reached."

             string tableName = randomTables[j % randomTables.Count];

             Console.Write("Creating root-level LTS " + j.ToString() + " selecting from " + tableName);
             using (var scope = new LocalTransactionScope(connectionString))
             using (var command = scope.CreateCommand())
             {
                 command.CommandType = CommandType.Text;
                 command.CommandText = "SELECT TOP 20 * FROM [" + tableName + "]";
                 using (var reader = command.ExecuteReader())
                 {
                     while (reader.Read())
                     {
                         Console.Write(".");
                     }
                     Console.Write(Environment.NewLine);
                 }
             }

             Thread.Sleep(50);
             scope.Complete();
         }

         Console.ReadKey();
     }
 }
4

2 に答える 2

4

MSDNによると、予想されるTransactionScope/SqlConnectionパターンは次のとおりです。

using(TransactionScope scope = ...) {
  using (SqlConnection conn = ...) {
    conn.Open();
    SqlCommand.Execute(...);
    SqlCommand.Execute(...);
  }
  scope.Complete();
}

したがって、MSDNの例では、スコープが完了する前に、接続がスコープ内に配置されます。コードは異なりますが、スコープが完了した後に接続を破棄します。私はTransactionScopeとそのSqlConnectionとの相互作用の専門家ではなく(私はいくつかのことを知っていますが、あなたの質問はかなり深くなります)、正しいパターンが何であるかについての仕様を見つけることができません。ただし、MSDNサンプルと同様に、コードを再検討し、最も外側のスコープが完了する前にシングルトン接続を破棄することをお勧めします。

また、2番目のスレッドがアプリケーションに組み込まれるとすぐに、コードがバラバラになることをご理解いただければ幸いです。

于 2010-02-08T18:49:58.510 に答える
0

このコードは合法ですか?

using(TransactionScope scope = ..)
{
    using (SqlConnection conn = ..)
    using (SqlCommand command = ..)
    {
        conn.Open();

        SqlCommand.Execute(..);
    }

    using (SqlConnection conn = ..) // the same connection string
    using (SqlCommand command = ..)
    {
        conn.Open();

        SqlCommand.Execute(..);
    }

    scope.Complete();
}
于 2010-07-15T07:34:08.207 に答える