Friday, 10 January 2014

Some Notes about TransactionScope in .NET

Basic usage of TransactionScope is as follow:
using (var scope = new TransactionScope())
{
    // some codes here . . .

    scope.Complete();
} 

By default, the isolation level used is Serializable and timeout is 1 minute.

According to this post on MSDN Blogs, the default isolation level is likely to introduce deadlock issues. The recommended isolation level is Read Committed.

If our codes are using more than one database (distributed transaction) then they will be much slower compare to only using one database (local transaction).

The maximum timeout of TransactionScope when setting this up via code (Timeout property) is 10 minutes. If we set the property to have a value larger than this, it would fall back to 10 minutes. If we want longer timeout value, we will need to set this in machine.config file. However that will affect other applications on the server.

Below is how to set isolation level and timeout in codes:
var transactionOptions = new TransactionOptions();
transactionOptions.IsolationLevel = IsolationLevel.ReadCommitted;
transactionOptions.Timeout = TransactionManager.MaximumTimeout;
var transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions);

If we want to change the timeout in machine.config:
<system.transactions>
   <machineSettings maxTimeout="00:30:00" />
</system.transactions>

When using SQL server, we also need to concern about the timeout of running query/command or stored procedure. The default timeout is 30 seconds. We can extend the timeout by setting CommandTimeout property.

No comments: