Reputation: 1
static void Main(string[] args)
{
bool bMethod1 = Metthod1();
bool bMethod2 = Metthod2();
bool bMethod3 = Metthod3();
if (!bMethod1 || !bMethod2 || !bMethod3)
{
//RollBack
}
}
I have a situation, where I want to rollback the work done by methods if any of the method returns false. I'm not doing any database related activity in my code, So is there any way to rollback/undo changes in C# 4.0 or above. I tried to use TransactionScope, but its not doing rollback. Other way I have thought of implementing my own rollback method which will manually undo all the changes(like if the file is copied, I will check the destination file and delete it using code). So is there any other workaround to solve this?
I have tried this so far.
static void Main(string[] args)
{
using (TransactionScope scope = new TransactionScope())
{
bool bMethod1 = Metthod1();
bool bMethod2 = Metthod2();
bool bMethod3 = Metthod3();
if (!bMethod1 || !bMethod2 || !bMethod3)
{
//RollBack
Transaction.Current.Rollback();
}
if (Transaction.Current.TransactionInformation.Status == TransactionStatus.Committed)
{
scope.Complete();
}
}
}
Upvotes: 0
Views: 183
Reputation: 7536
I think you better imlement Command Pattern yourself. Your 'transaction' if you can say so, basicaly is list of commands. Those commands can be executed only all at once. It is not so complex to implement.
Here is what I used when I needed this behavior:
public struct Command
{
public Action Upgrade;
public Action Downgrade;
}
public static void InvokeSafe(params Command[] commands)
{
var completed = new Stack<Command>();
try
{
foreach (var cmd in commands)
{
cmd.Upgrade();
completed.Push(cmd);
}
}
catch (Exception up)
{
try
{
foreach (var cmd in completed)
{
cmd.Downgrade();
}
}
catch (Exception down)
{
throw new AggregateException(up, down);
}
throw;
}
}
Then you call it like this:
int value = 3;
int modifier = 4;
InvokeSafe(new Command
{
Upgrade = () => { value += modifier; },
Downgrade = () => { value -= modifier; }
},
new Command
{
Upgrade = () => { value *= modifier; },
Downgrade = () => { value /= modifier; }
});
Upvotes: 2