How to determine whether a .NET exception is being handled?

前端 未结 5 579
生来不讨喜
生来不讨喜 2020-12-31 05:16

We\'re investigating a coding pattern in C# in which we\'d like to use a \"using\" clause with a special class, whose Dispose() method does different things dep

5条回答
  •  离开以前
    2020-12-31 06:15

    Not an answer to the question, but just a note that I never ended up using the "accepted" hack in real code, so it's still largely untested "in the wild". Instead we went for something like this:

    DoThings(x =>
    {
        x.DoSomething();
        x.DoMoreThings();
    });
    

    where

    public void DoThings(Action action)
    {
        bool success = false;
        try
        {
            action(new MyObject());
            Commit();
            success = true;
        }
        finally
        {
            if (!success)
                Rollback();
        }
    }
    

    The key point is that it's as compact as the "using" example in the question, and doesn't use any hacks.

    Among the drawbacks is a performance penalty (completely negligible in our case), and F10 stepping into DoThings when I actually want it to just step straight to x.DoSomething(). Both very minor.

提交回复
热议问题