Filip Ekberg
Filip Ekberg

Reputation: 36287

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?

Upvotes: 9

Views: 715

Answers (3)

thr
thr

Reputation: 19476

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

Upvotes: 3

Randy Minder
Randy Minder

Reputation: 48402

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

Upvotes: 6

Mark Seemann
Mark Seemann

Reputation: 233150

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

Upvotes: 11

Related Questions