Detecting a Dispose() from an exception inside using block

Posted by Augusto Radtke on Stack Overflow See other posts from Stack Overflow or by Augusto Radtke
Published on 2010-05-13T20:28:13Z Indexed on 2010/05/13 20:34 UTC
Read the original article Hit count: 361

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about using