22

I have the following code in my application:

using (var database = new Database()) {
    var poll = // Some database query code.

    foreach (Question question in poll.Questions) {
        foreach (Answer answer in question.Answers) {
            database.Remove(answer);
        }

        // This is a sample line  that simulate an error.
        throw new Exception("deu pau"); 

        database.Remove(question);
    }

    database.Remove(poll);
}

This code triggers the Database class Dispose() method as usual, and this method automatically commits the transaction to the database, but this leaves my database in an inconsistent state as the answers are erased but the question and the poll are not.

There is any way that I can detect in the Dispose() method that it being called because of an exception instead of regular end of the closing block, so I can automate the rollback?

I don´t want to manually add a try ... catch block, my objective is to use the using block as a logical safe transaction manager, so it commits to the database if the execution was clean or rollbacks if any exception occured.

Do you have some thoughts on that?

jball
  • 24,791
  • 9
  • 70
  • 92
Edwin Jarvis
  • 5,980
  • 6
  • 36
  • 41

8 Answers8

29

As others have said, your use of the Disposable pattern for this purpose is what is causing you the problems. If the pattern is working against you, then I would change the pattern. By making a commit the default behaviour of the using block, you are assuming that every use of a database results in a commit, which clearly is not the case - especially if an error occurs. An explicit commit, possibly combined with a try/catch block would work better.

However, if you really want to keep your use of the pattern as is, you can use:

bool isInException = Marshal.GetExceptionPointers() != IntPtr.Zero
                        || Marshal.GetExceptionCode() != 0;

in your Displose implementation to determine if an exception has been thrown (more details here).

adrianbanks
  • 81,306
  • 22
  • 176
  • 206
  • 8
    Adrian, you got it, I don´t want coaching about pattern usages, just a technical solution, it worked beautifully. – Edwin Jarvis May 14 '10 at 11:57
  • 1
    Please take a look at my answer. I try to explain why checking for exceptions inside a `Dispose` method is a bad idea. – Steven May 15 '10 at 12:38
  • 2
    @Steven: As most of the answers (including yours) have agreed, this is not a wise pattern to use. Even so, the original question asked whether it is *possible* to know whether an exception has been thrown when in a `Dispose` method, which is what my answer shows - even if it does have associated problems. – adrianbanks May 15 '10 at 14:44
  • I was looking for something similar to this to use and was actually doing almost the same thing your linked blog was doing with transactions. This worked perfectly, tested in production, and am enjoying it. It is better, in my opinion, to test for the need to rollback a transaction in one place as opposed to requiring every instance of the context to check for the need to roll back or to explicitly call for one. I tried other methods including reflection, thread tracing, and appdomain events, but this worked best - heck it was the only one that worked. Thanks! :D – Travis J Jul 17 '15 at 00:00
11

All others already wrote what the correct design of your Database class should be, so I won't repeat that. However, I didn't see any explanation why what you want to is not possible. So here it goes.

What you want to do is detect, during the call to Dispose, that this method is called in the context of an exception. When you would be able to do this, developers won't have to call Commit explicitly. However, the problem here is that there is no way to reliable detect this in .NET. While there are mechanisms to query the last thrown error (like HttpServerUtility.GetLastError), these mechanisms are host specific (so ASP.NET has an other mechanism as a windows forms for instance). And while you could write an implementation for a specific host implementation, for instance an implementation that would only work under ASP.NET, there is another more important problem: what if your Database class is used, or created within the context of an exception? Here is an example:

try
{
    // do something that might fail
}
catch (Exception ex)
{
    using (var database = new Database())
    {
        // Log the exception to the database
        database.Add(ex);
    } 
}

When your Database class is used in the context of an Exception, as in the example above, how is your Dispose method supposed to know that it still must commit? I can think of ways to go around this, but it will quite fragile and error prone. To give an example.

During creation of the Database, you could check whether it is called in the context of an exception, and if that’s the case, store that exception. During the time Dispose is called, you check whether the last thrown exception differs from the cached exception. If it differs, you should rollback. If not, commit.

While this seems a nice solution, what about this code example?

var logger = new Database();
try
{
    // do something that might fail
}
catch (Exception ex)
{
    logger.Add(ex);
    logger.Dispose();
}

In the example you see that a Database instance is created before the try block. Therefore is can not correctly detect that it sould not roll back. While this might be a contrived example, it shows the difficulties you will face when trying to design your class in a way no explicit call to Commit is needed.

In the end you will be making your Database class hard to design, hard to maintain, and you'll never really get it right.

As all others already said, a design that needs an explicit Commit or Complete call, would be easier to implement, easier to get right, easier to maintain, and gives usage code that is more readable (for instance, because it looks what developers expect).

Last note, if you're worried about developers forgetting to call this Commit method: you can do some checking in the Dispose method to see whether it is called without Commit is called and write to the console or set a breakpoint while debugging. Coding such a solution would still be much easier than trying to get rid of the Commit at all.

Update: Adrian wrote an intersting alternative to using HttpServerUtility.GetLastError. As Adrian notes, you can use Marshal.GetExceptionPointers() which is a generic way that would work on most hosts. Please note that this solution has the same drawbacks explained above and that calling the Marshal class is only possible in full trust

Community
  • 1
  • 1
Steven
  • 166,672
  • 24
  • 332
  • 435
  • How do you detect the exception in a call to `.Dispose()`? – Lasse V. Karlsen May 13 '10 at 21:54
  • @Lasse: As you can read in my answer, one possibility is by calling HttpServerUtility.GetLastError when your code is running in the ASP.NET host. – Steven May 14 '10 at 08:36
  • 1
    +1 for "What if you want to write to the database in the case of an exception" – cjk May 20 '10 at 11:14
  • 1
    It depends what the pattern is used for. I often use 'using' as a convenient way to embed performance counter start/stop event for instance. But committing or rolling back a DB transaction depending of the state of exception pointers is... I mean it's typically asking for trouble for no reason. – James Dingle Sep 15 '12 at 02:09
  • I really wish .NET had included an `IDisposableEx` interface with a `Dispose(Exception Ex)` method, and `using` would pass any exception which occurred to the `Dispose` method any exception that was causing program flow to transfer out of it. That would have allowed proper semantics to be implemented in cases that are otherwise difficult (e.g. if an unexpected exception kicks program flow out of a `using` block which is guarding a "write token" of a reader-writer lock, the safe behavior shouldn't be to cleanly release the lock, nor leave it dangling, but instead to... – supercat Jan 07 '14 at 23:11
  • *expressly invalidate* the lock, so that code waiting on it would immediately fail with an exception rather than assuming everything was okay or waiting forever on something that's never going to be available. – supercat Jan 07 '14 at 23:12
  • @supercat, this programming styoe should be rare. If you have many catch statements in your application you are probably doing something wrong. So I don't think having an IDisposableEx interface would be a good idea. – Steven Jan 07 '14 at 23:49
  • @Steven: Code should rarely *catch* unexpected exceptions, but that doesn't mean it should ignore them and hope code up the call stack knows what to do. If maintaining an object invariants requires that a lock be held while performing a certain sequence of steps, and the code which performs those steps exits via exception, then regardless of *why* the exception was thrown, the expected sequence cannot be expected to have run to completion, and the guarded object should be presumed invalid, *even if code up the call stack catches the exception and thinks everything is fine*. – supercat Jan 08 '14 at 00:04
  • @Steven: I would further posit that for things like transaction scopes, a `Dispose` which occurs as a consequence of an exception should silently roll back a transaction while letting the original exception propagate, but if `Dispose` which is executed in a non-exception case without an explicit commit or roll-back having been done first, throwing an exception would seem better than performing a silent rollback. – supercat Jan 08 '14 at 00:10
  • @supercat I'm not saying it's invalid to do so, but a pattern that is rare enough. Btw, if you're starting transactionscopes all over the place, you're definitely missing an abstraction and a decorator (aop). – Steven Jan 08 '14 at 00:40
  • @Steven: The pattern of invalidating objects on exceptions is rare, but the pattern of temporarily violating object invariants and then restoring them is *very* common, and I would posit that robust code should ensure that objects will be expressly invalidated if exceptions occur while invariants are violated. I would regard that as a good use for transaction scopes if there were some way they could tell why they were being exited. Acting upon a exceptions in such fashion may be "rare", but I would posit that it *shouldn't* be. – supercat Jan 08 '14 at 16:11
  • "what if your Database class is used, or created within the context of an exception?" - very good catch Steven! – nightcoder May 23 '16 at 18:48
7

Look at the design for TransactionScope in System.Transactions. Their method requires you to call Complete() on the transaction scope to commit the transaction. I would consider designing your Database class to follow the same pattern:

using (var db = new Database()) 
{
   ... // Do some work
   db.Commit();
}

You might want to introduce the concept of transactions outside of your Database object though. What happens if consumers want to use your class and do not want to use transactions and have everything auto commit?

Eric Hauser
  • 5,551
  • 3
  • 26
  • 29
2

In short: I think that's impossible, BUT

What you can do is to set a flag on your Database class with default value "false" (it's not good to go) and on the last line inside using block you call a method that sets it to "true", then in the Dispose() method you may check whether the flag "has exception" or not.

using (var db = new Database())
{
    // Do stuff

    db.Commit(); // Just set the flag to "true" (it's good to go)
}

And the database class

public class Database
{
    // Your stuff

    private bool clean = false;

    public void Commit()
    {
        this.clean = true;
    }

    public void Dispose()
    {
        if (this.clean == true)
            CommitToDatabase();
        else
            Rollback();
    }
}
BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • Unfortunately this is not a proper design of a class. `Dispose` should do as little as possible. When you're doing more than just disposing resources in a `Dispose` method, the changes of an exception being thrown from that `Dispose` method are higher. `Dispose` is also called in the context of an `Exception`, and in that case you would be replacing that exception with a new one, making debugging, and finding the cause of the exception, harder. Also, don't actively rollback a db transaction in a `Dispose` because of the same reasion. Just dispose the underlying transaction. – Steven May 14 '10 at 08:43
  • I guess this comment should be on the question, not on my answer, but anyway... "Dispose is also called in the context of an Exception" he knows that, and that's why he wants to find out if there were or not an exception, and instead of throw a exception again he would have a try catch around CommitToDatabase and Rollback or something like that – BrunoLM May 14 '10 at 10:08
  • I commented on the code I saw in your answer, but you're right about that: My comment would indeed be more appropriate on the question itself. btw. It is very hard to get the design right when trying to do this without an explicit `Commit` method, as I tried to explain in my answer: http://stackoverflow.com/questions/2830073/detecting-a-dispose-from-an-exception-inside-using-block/2830501#2830501 – Steven May 15 '10 at 11:50
1

Sound like you need TransactionScope http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx

Oskar Kjellin
  • 21,280
  • 10
  • 54
  • 93
1

You should wrap the contents of your using block in a try/catch and roll back the transaction in the catch block:

using (var database = new Database()) try
{
    var poll = // Some database query code.

    foreach (Question question in poll.Questions) {
        foreach (Answer answer in question.Answers) {
            database.Remove(answer);
        }

        // This is a sample line  that simulate an error.
        throw new Exception("deu pau"); 

        database.Remove(question);
    }

    database.Remove(poll);
}
catch( /*...Expected exception type here */ )
{
    database.Rollback();
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • I don´t want to, I want to use "using" as a helper for that operation, with addiction of other boilerplate that I have to make. – Edwin Jarvis May 13 '10 at 20:36
  • @Augusto - rollback works well with "using". See my updated answer – Joel Coehoorn May 13 '10 at 20:42
  • 3
    Using is simply a shortcut syntax for try{} finally{ o.Dispose() } Replacing the using with a single try{} catch{ rollback } finally{ dispose } is the correct thing to do. – chilltemp May 13 '10 at 20:46
  • I tried to explain in my answer why a class design without an explicit `Complete` or `Commit` method is possible: http://stackoverflow.com/questions/2830073/detecting-a-dispose-from-an-exception-inside-using-block/2830501#2830501 – Steven May 15 '10 at 11:53
1

As Anthony points out above, the problem is a fault in your use of the using clause in this scenario. The IDisposable paradigm is meant to ensure that an object's resources are cleaned up regardless of the outcome of a scenario (thus why an exception, return, or other event that leaves the using block still triggers the Dispose method). But you've repurposed it to mean something different, to commit the transaction.

My suggestion would be as others have stated and use the same paradigm as TransactionScope. The developer should have to explicitly call a Commit or similar method at the end of the transaction (before the using block closes) to explicitly say that the transaction is good and ready to be committed. Thus, if an exception causes execution to leave the using block, the Dispose method in this case can do a Rollback instead. This still fits in the paradigm, since doing a Rollback would be a way of "cleaning up" the Database object so that it is not left an invalid state.

This shift in design would also make it much easier to do what you want to do, since you won't be fighting the design of .NET to try and "detect" an exception.

0

You could inherit from the Database class and then override the Dispose() method (making sure to close the db resources), this could then raise a custom event to which you can subscribe in your code.

David Neale
  • 16,498
  • 6
  • 59
  • 85