Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transaction in pure C# coding [duplicate]

Tags:

c#

.net

I wonder if there is a simple manner to handle some kind of transaction in C#. Let us say that we have two properties and we would like to update their values. We could write:

A = GetA();
B = GetB();

The problem is, that if the exception will be thrown while assigning B, then object will be in inconsistant state, because A has been updated. We can solve this by storing the current value of A and catching an exception when dealing with B:

var tempA = A;
A = GetA(); // A is up to date
try { B = GetB(); } catch { A = tempA; } // B is up to date also or A is reverted

Even above solution is not save because the exception can be thrown while reverting A, but the point is, if there are built in mechanisms in .NET that simplyfies such operations?

I could imagine a statement like the below:

transaction { A = GetA(); B = GetB(); }

Or code construction like:

Transaction.Enter();
A = GetA();
B = GetB();
Transaction.Leave();

Before transaction the machine state will be stored and after transaction it will be reverted in case of exception. Is there something like that in .NET?

like image 942
Ryszard Dżegan Avatar asked Jul 29 '13 12:07

Ryszard Dżegan


2 Answers

"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 "

Source: https://stackoverflow.com/a/2273902/1714342

I think you can implement this IEnlistmentNotification interface and use TransactionScope

like image 187
Kamil Budziewski Avatar answered Sep 20 '22 16:09

Kamil Budziewski


You can use TransactionScope class.

Example:

using(var scope = new TransactionScope())
{
    DoAction1();
    DoAction2();

    scope.Complete();
}
like image 29
Tamim Al Manaseer Avatar answered Sep 22 '22 16:09

Tamim Al Manaseer