从 using 块内的异常中检测 Dispose()

发布于 2024-09-02 00:04:51 字数 725 浏览 7 评论 0原文

我的应用程序中有以下代码:

using (var database = new Database()) {
    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);
}

此代码像往常一样触发数据库类 Dispose() 方法,并且此方法自动将事务提交到数据库,但这使我的数据库处于不一致的状态,因为答案被删除但问题而民意调查则不然。

有什么方法可以在 Dispose() 方法中检测到它是由于异常而不是关闭块的常规结尾而被调用的,这样我就可以自动回滚?

我不想手动添加 try ... catch 块,我的目标是使用 using 块作为逻辑安全事务管理器,因此如果执行干净,它会提交到数据库,如果发生任何异常,它会回滚。

您对此有什么想法吗?

I have the following code in my application:

using (var database = new Database()) {
    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);
}

This code triggers the Database class Dispose() method as usual, and this method automatically commits the transaction to the database, but this leaves my database in an inconsistent state as the answers are erased but the question and the poll are not.

There is any way that I can detect in the Dispose() method that it being called because of an exception instead of regular end of the closing block, so I can automate the rollback?

I don´t want to manually add a try ... catch block, my objective is to use the using block as a logical safe transaction manager, so it commits to the database if the execution was clean or rollbacks if any exception occured.

Do you have some thoughts on that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

命硬 2024-09-09 00:04:51

正如其他人所说,您为此目的使用一次性模式是导致问题的原因。如果这个模式对你不利,那么我会改变这个模式。通过将提交设置为 using 块的默认行为,您假设每次使用数据库都会导致提交,但事实显然并非如此 - 特别是在发生错误时。显式提交(可能与 try/catch 块结合使用)效果会更好。

但是,如果您确实想按原样保留该模式的使用,您可以

bool isInException = Marshal.GetExceptionPointers() != IntPtr.Zero
                        || Marshal.GetExceptionCode() != 0;

在 Displose 实现中使用:来确定是否已引发异常(更多详细信息 此处)。

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).

傲性难收 2024-09-09 00:04:51

所有其他人都已经写过 Database 类的正确设计应该是什么,所以我不会重复。但是,我没有看到任何解释为什么你想要的东西是不可能的。所以就这样了。

您想要做的是在调用 Dispose 期间检测是否在异常上下文中调用此方法。当您能够执行此操作时,开发人员将不必显式调用 Commit。然而,这里的问题是在 .NET 中没有办法可靠地检测到这一点。虽然有一些机制可以查询最后抛出的错误(例如 HttpServerUtility.GetLastError),这些机制是特定于主机的(因此 ASP.NET 有其他机制,例如 Windows 窗体)。虽然您可以为特定主机实现编写实现,例如只能在 ASP.NET 下工作的实现,但还有另一个更重要的问题:如果使用您的 Database 类会怎样? ,还是在异常上下文中创建?这是一个示例:

try
{
    // do something that might fail
}
catch (Exception ex)
{
    using (var database = new Database())
    {
        // Log the exception to the database
        database.Add(ex);
    } 
}

当您的 Database 类在 Exception 上下文中使用时,如示例中所示如上所述,您的 Dispose 方法如何知道它仍然必须提交?我可以想出解决这个问题的方法,但它会非常脆弱并且容易出错。举个例子。

在创建数据库期间,您可以检查是否在异常上下文中调用它,如果是这样,则存储该异常。在调用 Dispose 期间,您检查最后抛出的异常是否与缓存的异常不同。如果不同,则应该回滚。如果没有,请提交。

虽然这看起来是一个不错的解决方案,但是这个代码示例怎么样?

var logger = new Database();
try
{
    // do something that might fail
}
catch (Exception ex)
{
    logger.Add(ex);
    logger.Dispose();
}

在示例中,您会看到在 try 块之前创建了一个 Database 实例。因此无法正确检测到它不应该回滚。虽然这可能是一个人为的示例,但它显示了在尝试以不需要显式调用 Commit 的方式设计类时将面临的困难。

最终,您将使您的 Database 类变得难以设计、难以维护,而且您永远无法真正做到正确。

正如所有其他人已经说过的,需要显式 CommitComplete 调用的设计将更容易实现,更容易正确,更容易维护,并提供使用代码这更具可读性(例如,因为它看起来符合开发人员的期望)。

最后一点,如果您担心开发人员忘记调用此 Commit 方法:您可以在 Dispose 方法中进行一些检查,看看是否在没有 的情况下调用了该方法Commit 被调用并写入控制台或在调试时设置断点。编写这样的解决方案仍然比尝试完全摆脱 Commit 容易得多。

更新:
Adrian 编写了一个有趣的替代方案使用 HttpServerUtility.GetLastError。正如 Adrian 所说,您可以使用 Marshal.GetExceptionPointers() ,这是适用于大多数主机的通用方法。请注意,此解决方案具有与上述相同的缺点,并且只有在完全信任的情况下才能调用 Marshal

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

┼── 2024-09-09 00:04:51

查看 System.Transactions 中 TransactionScope 的设计。他们的方法要求您在事务范围上调用 Complete() 来提交事务。我会考虑设计您的数据库类以遵循相同的模式:

using (var db = new Database()) 
{
   ... // Do some work
   db.Commit();
}

不过,您可能希望在数据库对象之外引入事务的概念。如果消费者想要使用您的类并且不想使用事务并且让所有内容自动提交,会发生什么?

Look at the design for TransactionScope in System.Transactions. Their method requires you to call Complete() on the transaction scope to commit the transaction. I would consider designing your Database class to follow the same pattern:

using (var db = new Database()) 
{
   ... // Do some work
   db.Commit();
}

You might want to introduce the concept of transactions outside of your Database object though. What happens if consumers want to use your class and do not want to use transactions and have everything auto commit?

温柔少女心 2024-09-09 00:04:51

简而言之:我认为这是不可能的,但是

您可以做的是在 Database 类上设置一个默认值“false”的标志(这不好),并在 using 块内的最后一行调用一个设置它的方法设置为“true”,然后在 Dispose() 方法中您可以检查标志是否“有异常”。

using (var db = new Database())
{
    // Do stuff

    db.Commit(); // Just set the flag to "true" (it's good to go)
}

和数据库类

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

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();
    }
}
黑白记忆 2024-09-09 00:04:51

您应该将 using 块的内容包装在 try/catch 中,并回滚 catch 块中的事务:

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

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();
}
七颜 2024-09-09 00:04:51

正如安东尼上面指出的,问题是在这种情况下使用 using 子句的错误。 IDisposable 范例旨在确保无论场景结果如何(因此异常、返回或离开 using 块的其他事件仍然会触发 Dispose 方法),对象的资源都会被清理。但您已将其重新调整为不同的含义,即提交事务。

我的建议是像其他人所说的那样并使用与 TransactionScope 相同的范例。开发人员应该必须在事务结束时(在 using 块关闭之前)显式调用 Commit 或类似方法,以显式表明事务正常并准备好提交。因此,如果异常导致执行离开 using 块,在这种情况下,Dispose 方法可以执行 Rollback。这仍然符合该范例,因为执行回滚将是“清理”数据库对象的一种方法,以便它不会留下无效状态。

这种设计上的转变也将使您更容易做您想做的事情,因为您不会为了尝试“检测”异常而与 .NET 的设计作斗争。

As Anthony points out above, the problem is a fault in your use of the using clause in this scenario. The IDisposable paradigm is meant to ensure that an object's resources are cleaned up regardless of the outcome of a scenario (thus why an exception, return, or other event that leaves the using block still triggers the Dispose method). But you've repurposed it to mean something different, to commit the transaction.

My suggestion would be as others have stated and use the same paradigm as TransactionScope. The developer should have to explicitly call a Commit or similar method at the end of the transaction (before the using block closes) to explicitly say that the transaction is good and ready to be committed. Thus, if an exception causes execution to leave the using block, the Dispose method in this case can do a Rollback instead. This still fits in the paradigm, since doing a Rollback would be a way of "cleaning up" the Database object so that it is not left an invalid state.

This shift in design would also make it much easier to do what you want to do, since you won't be fighting the design of .NET to try and "detect" an exception.

黎歌 2024-09-09 00:04:51

您可以从 Database 类继承,然后重写 Dispose() 方法(确保关闭数据库资源),这可能会引发一个您可以在代码中订阅的自定义事件。

You could inherit from the Database class and then override the Dispose() method (making sure to close the db resources), this could then raise a custom event to which you can subscribe in your code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文