C# .NET: Set a Timeout on a .NET Transaction

7/11/2014 11:18:07 PM

Set the timeout in seconds for a .NET Transaction

int timeoutInSeconds;
TimeSpan transactionTimeout = TimeSpan.FromSeconds(timeoutInSeconds);
var transactionOptions = new System.Transactions.TransactionOptions();
transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
transactionOptions.Timeout = transactionTimeout;

using (System.Transactions.TransactionScope transaction = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOptions))
{
	try
	{
		//do something
	}
	catch (Exception ex)
	{                    
		_log4net.Error("Dammit!!!", ex);
	 
		//returning prior to call transaction.Complete(); will roll back the transaction
		throw ex;
	}

	//transaction completed successfully, all calls succeeded
	transaction.Complete();
}//transaction end