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?
"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
You can use TransactionScope class.
Example:
using(var scope = new TransactionScope())
{
DoAction1();
DoAction2();
scope.Complete();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With