Transaction in pure C # coding

I wonder if there is an easy way to handle any transaction in C #. Let's 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 an exception is thrown when assigning B, then the object will be in an inconsistent state since A has been updated. We can solve this by storing the current value of A and catching an exception when working 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 the solution above is not saved, because an exception can be thrown when A returns, but the fact is, are there any built-in mechanisms in .NET that simplify such operations?

I could imagine an expression like the one below:

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

Or code building, for example:

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

Before the transaction, the state of the device will be saved, and after the transaction it will be canceled in case of an exception. Is there something similar in .NET?

+4
source share
3 answers

"TransactionScope is not just for databases. Each component that implements the IEnlistmentNotification interface can participate in two-phase commit of the transaction area.

The following is an example of a transactional storage in memory: http://www.codeproject.com/KB/dotnet/Transactional_Repository.aspx "

Source: fooobar.com/questions/363311 / ...

I think you can implement this IEnlistmentNotification interface and use TransactionScope

+9
source

You can use the TransactionScope class.

Example:

 using(var scope = new TransactionScope()) { DoAction1(); DoAction2(); scope.Complete(); } 
+4
source

There is no built-in function for object transactions. But there are some third-party libraries that provide this to support object state management.

You can take a look at this similar question.

fooobar.com/questions/254113 / ...

+2
source

Source: https://habr.com/ru/post/1494059/


All Articles