views:

239

answers:

3
+8  Q: 

Transactions in C#

First of all, this will not be a post about Database Transactions. I want to know more about the TransactionModel in .NET 2.0 and higher. Since I am developing against .NET 3.5 newer models are apprechiated.

Now, what I would like to acheive is something like the following

    public void Withdraw(double amount)
    {
        using (TransactionScope scope = new TransactionScope())
        {
            Money -= amount;

            if (Money > 0)
                scope.Complete();
        }
    }

Which would mean that when the Money is less than 0, everything inside the TransactionScope should be RolledBack, however, it's not.

A simple test as followed

        ImportantObject obj = new ImportantObject(1);

        Console.WriteLine(obj.Money);

        obj.Withdraw(101);

        Console.WriteLine(obj.Money);

Provided that the Stadard Money amount is 100.

Did I miss something here or is this not how the transactions should work? And what are the performance losses using this model?

+10  A: 

You may want to read Volatile Resource Managers in .NET: Bring Transactions to the Common Type by Juval Lowy.

Mark Seemann
+5  A: 

I think you are confused with what TransactionScope is designed to do. TransactionScope is designed to commit or rollback changes in the database you are connected to. It does not reverse changes to objects in code. It will not reverse the value contained in 'Money'.

Randy

Randy Minder
+3  A: 

What you're after is called STM, Software Transactional Memory. Check out http://research.microsoft.com/en-us/downloads/6cfc842d-1c16-4739-afaf-edb35f544384/default.aspx

thr
Seems like this is what I've been looking for. Thanks.
Filip Ekberg