Detecting a Dispose() from an exception inside using block

前端 未结 8 501
暖寄归人
暖寄归人 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:33

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

提交回复
热议问题