.net – 在分布式事务中手动登记后,使用enlist = false的连接不会关闭

我有一个使用ServiceDomain的分布式事务上下文.在其中,我使用指定Enlist = false的连接字符串打开SQL连接,以便它不会自动登记在事务中.然后,如果我使用EnlistDistributedTransaction手动登记分布式事务中的连接,则连接不会关闭,这可能以InvalidOperationException结束:

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.

请尝试以下方法:

try
{
    var configuration = new ServiceConfig
        {
            Transaction = TransactionOption.Required,
            TransactionTimeout = 1000
        };
    ServiceDomain.Enter(configuration);

    for (var i = 0; i < 500; ++i)
    {
        Console.WriteLine(i);
        using (var conn = new SqlConnection("Data Source=localhost;Initial Catalog=dotest;Integrated Security=SSPI;Enlist=False;"))
        {
            conn.Open();
            if (i % 2 == 0) conn.EnlistDistributedTransaction((ITransaction) ContextUtil.Transaction);
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandText = "INSERT INTO [Test]([ID]) VALUES(@num)";
                cmd.Parameters.AddWithValue("@num", i);
                cmd.ExecuteNonQuery();
            }
        }
    }

    ContextUtil.SetAbort();
}
finally
{
    ServiceDomain.Leave();
}

这会在200个连接处卡住(并在超时后死亡),因为所有100个登记的连接显然都没有关闭(并且默认连接池大小为100). (请注意,如果要在不创建表的情况下进行测试,则可以完全删除该命令.)

我错过了什么或做错了什么?

尝试设置conn.EnlistDistributedTransaction(null);在查询执行结束时.

using (var conn = new SqlConnection("Data Source=localhost;Initial Catalog=dotest;Integrated Security=SSPI;Enlist=False;"))
{
    conn.Open();
    if (i % 2 == 0) conn.EnlistDistributedTransaction((ITransaction) ContextUtil.Transaction);
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "INSERT INTO [Test]([ID]) VALUES(@num)";
        cmd.Parameters.AddWithValue("@num", i);
        cmd.ExecuteNonQuery();
    }
   conn.EnlistDistributedTransaction(null);
}
相关文章
相关标签/搜索