views:

1000

answers:

2

I have this code, running parallel in two separate threads. It works fine for a few times, but at some random point it throws InvalidOperationException:

The transaction is either not associated with the current connection or has been completed.

At the point of exception, I am looking inside the transaction with visual studio and verify its connection is set normally. Also command.Transaction._internalTransaction. _transactionState is set to Active and IsZombied property is set to false.

This is a test application and I am using Thread.Sleep for creating longer transactions and causing overlaps.

Why may the exception being thrown and what can I do about it?

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();
}
A: 

Found the solution. Turns out calling this

command.Connection = connection;

does not mean that you set the connection to the command. Just after calling this, I checked the results of

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

and they were not equal. Refacotored the code to use connection.CreateCommand and the problem solved.

Serhat Özgel
A: 

It doesn't seem to solve the problem for me... i still get the same error.

related questions