私は賢いと思っていました。しかし、最近の発見に照らして、私はもうよくわかりません。ページのライフサイクル中に、データベースの相互作用がいくつも発生する可能性があります。背中合わせにあるものもあれば、広がるものもあります。そこで、HttpContext.ItemsディクショナリでSQL接続のインスタンスを存続させるオブジェクトを発明しました。その後、すべてのdbリクエストはこの接続を使用し、httpリクエストが終了すると、接続を適切に破棄します。接続が開いている数百ミリ秒を見ています。httpキャッシングが多い場合、使用可能な接続が不足することは問題ではありません。
ポイントは、新しい接続の確立による追加のラウンドトリップを防ぐことでした。しかし、接続プールの知識に出くわしたとき、それはSqlConnectionを保持することの有用性をかなり無効にすると思います。それともそうですか?
シナリオAはシナリオBと同じですか、パフォーマンスの面でですか?どちらをお勧めしますか?シナリオBはパフォーマンスの向上をもたらさず、接続が適切に破棄されない可能性があるいくつかのエッジケースのために、パフォーマンスを妨げる可能性さえありますか?例の疑似性を許してください、私はそれらをbarfで乱雑にしたくありません。
A
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand("...", connection))
{
... doing database stuff ...
}
}
... traversing the stack ...
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand("...", connection))
{
... doing database stuff ...
}
}
B
var connectionKeeper = new ConnectionKeeper();
// Add to the context items so it can be used anywhere
Context.Items.Add("Connection", connectionKeeper);
... traversing the stack ...
using (var command = new SqlCommand("...", connectionKeeper.Connection))
{
... doing database stuff
}
... traversing the stack ...
using (var command = new SqlCommand("...", connectionKeeper.Connection))
{
... doing database stuff
}
... traversing the stack ...
// The end of the request
sqlKeeper.Dispose();