Possible Duplicate:
Transactions for C# objects?
My question is – what is the best way to ensure that either ALL code in a given segment is executed or nothing is executed at all? Try Catch wouldn’t work in this case because if line 1 is update, it will take place, then if line 2 is send email and that fails for some reason, it’ll then throw the exception, but the update will have taken place already (whereas what I want is something like this –> if line 40 fails, do not execute line 20).
I know that on the database side you can use Transactions, but I was wondering if there was an equivalent of that in code…
Transactions ensure atomicity by performing roll-backs in case of error. But not all actions can be rolled back, for example, sending a mail. Its an arrow out of the bow, not coming back.
Short answer is that this cannot be done.
UPDATE:
@JustinNiessner’s comment above links to this excellent question that suggests some work in this area. But note that it cannot be guaranteed except in simplest cases. Specifically, it is probably very difficult to rollback i/o side-effects.