Pages

Advertisement

Wednesday, July 11, 2007

Managing Transactions with a Stack

public void BeginTransaction()
{
SqlTransaction currentTrans = currentConnection.BeginTransaction();
transactions.Push(currentTrans);
}

public void RollbackTransaction()
{
SqlTransaction currentTrans;
while (transactions.Count > 0)
{
currentTrans = (SqlTransaction)transactions.Pop();
currentTrans.Rollback();
}
}

public void CommitTransaction()
{
SqlTransaction currentTrans = (SqlTransaction)transactions.Peek();
currentTrans.Commit();
transactions.Pop();
}

public SqlTransaction CurrentTransaction
{
get
{
if (transactions.Count > 0)
return (SqlTransaction)transactions.Peek();
else
return null;
}
}

I have the transactions variable declared as:

private Stack transactions = new Stack();

Each time I run a function within the Database class, I look to see whether the CurrentTransaction is null; if not, I set the Transaction property of each SqlCommand object equal to it. This enlists the command in the transaction. When I'm done with all my work, I call CommitTransaction, which commits the current transaction to the database. If any errors occur, I can call RollbackTransaction, which rolls back all pending transactions. A failure in one part of the transaction means the entire thing needs to be undone in this model.

In regards to using the Stack object, the Peek method returns the top object without removing it from the stack; doing this lets you use the object without removing it from the stack, because a transaction may have three or four actions before it's complete.

No comments: