Detecting a Dispose() from an exception inside using block

前端 未结 8 515
暖寄归人
暖寄归人 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: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).

提交回复
热议问题