0

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...

Community
  • 1
  • 1
pnduke
  • 183
  • 3
  • 15
  • You'd probably have to implement a mechanism that tracked everything that changed, and *rolled it back* if the operation fails. There's nothing in the runtime that can magically do that for you. – Mike Christensen Jan 25 '13 at 18:12
  • 1
    Maybe [STM](http://en.wikipedia.org/wiki/Software_transactional_memory) or [compensating transaction](http://blogs.msdn.com/b/rogerwolterblog/archive/2006/05/24/606184.aspx) – rene Jan 25 '13 at 18:13
  • 1
    Sounds like you have some side-effects and/or possible global state. Try eliminating those. And when exceptions happen, that should be your cue to abort everything, anyway, unless you absolutely know it is something you can recover from. – Anthony Pegram Jan 25 '13 at 18:20

2 Answers2

5

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.

Community
  • 1
  • 1
Miserable Variable
  • 28,432
  • 15
  • 72
  • 133
  • Well, if you have a Mail resource manager that only sends mails on commit, sending an email *can* be undone... – zmbq Jan 25 '13 at 23:36
0

In general, there is nothing that can rollback any statement you write.

But it is possible to add support transactions to some specific pieces of your code. In this case distributed transactions might be useful.

svick
  • 236,525
  • 50
  • 385
  • 514
  • There is nothing that can rollback any statement you write automatically, but one can write their own rollback functions. – PmanAce Jan 25 '13 at 18:41