jonathanpeppers
jonathanpeppers

Reputation: 26495

C# - System.Transactions.TransactionScope

I was curious about the TransactionScope class.

For the most part, I assume it was intended for database connections (which is what I've used it for).

My question, is can you put any code in the using-block of a TransactionScope to make it transactional? MS documentation is not clear on this.

If it can be used to make code other than database connections transactional, which ones are supported? It would seem crazy to me if it could make System.IO.File operations transactional.

Upvotes: 14

Views: 12031

Answers (2)

Vitaliy Liptchinsky
Vitaliy Liptchinsky

Reputation: 5299

TransactionScope is not only for the databases. Every component that implements IEnlistmentNotification interface can participate in two-phase commit of the transaction scope.

Here is an example of transactional in-memory storage: http://www.codeproject.com/KB/dotnet/Transactional_Repository.aspx

Also, I'm not sure if there are components in .NET for transactional file IO, but it is pretty easy to implement such component - latest OS like Vista and Windows Server 2008 have support for transaction file IO.

Upvotes: 13

Jeff Sternal
Jeff Sternal

Reputation: 48583

No, you cannot make arbitrary code transactional by running it inside a TransactionScope.

As you noted in a comment, the System.Transactions namespace provides infrastructure classes to help make any resource transactional. By default, .NET provides resource manager support for several kinds of operations, listed in the namespace introduction you linked (in a comment): "SQL Server, ADO.NET, MSMQ, and the Microsoft Distributed Transaction Coordinator (MSDTC)."

It turns out, there is support for file system transactions - though I could only find it for NTFS (Enhance Your Apps With File System Transactions). For my money, that code could seriously use a façade, though. ;) Perhaps there are other, more generalized implementations out there (or perhaps not - making file IO transactional may require the extra infrastructure NTFS provides).

There's also a fair amount of ongoing research on making changes to in-memory state transactional, called software transactional memory. Microsoft DevLabs offers an implementation: STM.NET.

Upvotes: 6

Related Questions