Detecting a Dispose() from an exception inside using block

前端 未结 8 507
暖寄归人
暖寄归人 2021-02-01 19:13

I have the following code in my application:

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

    foreach (Question question          


        
8条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-01 19:44

    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();
        }
    }
    

提交回复
热议问题