2

我有这段代码,在两个单独的线程中并行运行。它可以正常工作几次,但在某个随机点抛出InvalidOperationException:InvalidOperationException在执行事务时执行SqlCommand

事务要么不与当前连接关联,要么已经完成。

在例外情况下,我正在使用visual studio查看事务内部并验证其连接是否正常设置。也是command.Transaction._internalTransaction。 _transactionState设置为活动,IsZombied属性设置为false。

这是一个测试应用程序,我使用Thread.Sleep创建更长的事务并导致重叠。

为什么可能抛出异常,我该怎么办?

IDbCommand command = new SqlCommand("Select * From INFO"); 
IDbConnection connection = new SqlConnection(connectionString); 
command.Connection = connection; 
IDbTransaction transaction = null; 
try 
{ 
    connection.Open(); 
    transaction = connection.BeginTransaction(); 
    command.Transaction = transaction; 
    command.ExecuteNonQuery(); // Sometimes throws exception 
    Thread.Sleep(forawhile); // For overlapping transactions running in parallel 
    transaction.Commit(); 
} 
catch (ApplicationException exception) 
{ 
    if (transaction != null) 
    { 
     transaction.Rollback(); 
    } 
} 
finally 
{ 
    connection.Close(); 
} 

回答

2

找到解决方案。原来叫这个

command.Connection = connection; 

并不意味着你设置连接到命令。刚打完电话后,我检查了结果

command.Connection.GetHashCode(); 
command.GetHashCode(); 

他们不一样。 Refacotored代码使用connection.CreateCommand和问题解决。

相关问题