Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 243
Filip Ekberg Avatar asked Jan 07 '10 13:01

Filip Ekberg


People also ask

What is transaction in C language?

Introduction to the C Language Application-Transaction Monitor Interface. Description. The application-transaction monitor interface provides the interface between the application and the transaction processing system. This interface is known as the ATMI interface.

What is transaction explain with example?

A Transaction is any process a user performs after successfully logging in. Examples of Transactions are making a purchase, bill pay, money transfer, stock trade, address change, and others. With each type of Transaction, different type of details are involved.

What are types of transactions in database?

Three DBMS transactions types are Base on Application Areas, Action, & Structure.

What is transaction and how it works?

A transaction is a logical unit of work (comprising one or more SQL statements) performed on the database to complete a common task and maintain data consistency. Transaction statements are closely related and perform interdependent actions.


3 Answers

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

like image 113
Mark Seemann Avatar answered Oct 02 '22 20:10

Mark Seemann


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

like image 41
Randy Minder Avatar answered Oct 02 '22 22:10

Randy Minder


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

like image 21
thr Avatar answered Oct 02 '22 20:10

thr