Detecting a Dispose() from an exception inside using block

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

    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

提交回复
热议问题