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?
source share