Bill Brown
Bill Brown

Reputation: 145

The operation is not valid for the state of the transaction

I have a TransactionScope() block. It always gets stuck in an insert statement. It appears in the Activity Monitor as a Blocking Task, so it blocks the SQL server, and after the timeout, I get this error:

The operation is not valid for the state of the transaction.

What’s going wrong?

const TransactionScopeOption opt = new TransactionScopeOption();
TimeSpan span = new TimeSpan(0, 0, 1, 30);

try
{
    using (TransactionScope scope01 = new TransactionScope(opt, span))
    {
        using (var sqlcon = new SqlConnection(sSqlCon))
        {
            //select,insert , update statements
        }
    }
}
catch (Exception ex)
{
}

Upvotes: 3

Views: 19947

Answers (2)

Chinthaka Fernando
Chinthaka Fernando

Reputation: 814

The transaction might have been timed out. check the maching.config for the default time out

<configuration> 
  <system.transactions>
    <machinesettings maxtimeout="00:30:00" />
  </system.transactions>
</configuration> 

Upvotes: 0

MilkTea027
MilkTea027

Reputation: 301

It probably means it aborted. Did you call transaction complete within transaction bracket?

try
{
    using (TransactionScope scope01 = new TransactionScope(opt, span))
    {
        using (var sqlcon = new SqlConnection(sSqlCon))
        {
            //select,insert , update statements
        }

        scope01.Complete();
    }
}

If it doesn't call the Complete, it will automatically rollback.

Upvotes: 2

Related Questions