从 using 块内的异常中检测 Dispose()
我的应用程序中有以下代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
正如其他人所说,您为此目的使用一次性模式是导致问题的原因。如果这个模式对你不利,那么我会改变这个模式。通过将提交设置为 using 块的默认行为,您假设每次使用数据库都会导致提交,但事实显然并非如此 - 特别是在发生错误时。显式提交(可能与 try/catch 块结合使用)效果会更好。
但是,如果您确实想按原样保留该模式的使用,您可以
在 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:
in your Displose implementation to determine if an exception has been thrown (more details here).
所有其他人都已经写过
Database
类的正确设计应该是什么,所以我不会重复。但是,我没有看到任何解释为什么你想要的东西是不可能的。所以就这样了。您想要做的是在调用
Dispose
期间检测是否在异常上下文中调用此方法。当您能够执行此操作时,开发人员将不必显式调用Commit
。然而,这里的问题是在 .NET 中没有办法可靠地检测到这一点。虽然有一些机制可以查询最后抛出的错误(例如 HttpServerUtility.GetLastError),这些机制是特定于主机的(因此 ASP.NET 有其他机制,例如 Windows 窗体)。虽然您可以为特定主机实现编写实现,例如只能在 ASP.NET 下工作的实现,但还有另一个更重要的问题:如果使用您的Database
类会怎样? ,还是在异常上下文中创建?这是一个示例:当您的
Database
类在Exception
上下文中使用时,如示例中所示如上所述,您的 Dispose 方法如何知道它仍然必须提交?我可以想出解决这个问题的方法,但它会非常脆弱并且容易出错。举个例子。在创建数据库期间,您可以检查是否在异常上下文中调用它,如果是这样,则存储该异常。在调用
Dispose
期间,您检查最后抛出的异常是否与缓存的异常不同。如果不同,则应该回滚。如果没有,请提交。虽然这看起来是一个不错的解决方案,但是这个代码示例怎么样?
在示例中,您会看到在 try 块之前创建了一个
Database
实例。因此无法正确检测到它不应该回滚。虽然这可能是一个人为的示例,但它显示了在尝试以不需要显式调用Commit
的方式设计类时将面临的困难。最终,您将使您的
Database
类变得难以设计、难以维护,而且您永远无法真正做到正确。正如所有其他人已经说过的,需要显式
Commit
或Complete
调用的设计将更容易实现,更容易正确,更容易维护,并提供使用代码这更具可读性(例如,因为它看起来符合开发人员的期望)。最后一点,如果您担心开发人员忘记调用此
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 callCommit
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 yourDatabase
class is used, or created within the context of an exception? Here is an example:When your
Database
class is used in the context of anException
, as in the example above, how is yourDispose
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 timeDispose
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?
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 toCommit
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
orComplete
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 theDispose
method to see whether it is called withoutCommit
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 theCommit
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 theMarshal
class is only possible in full trust查看 System.Transactions 中 TransactionScope 的设计。他们的方法要求您在事务范围上调用 Complete() 来提交事务。我会考虑设计您的数据库类以遵循相同的模式:
不过,您可能希望在数据库对象之外引入事务的概念。如果消费者想要使用您的类并且不想使用事务并且让所有内容自动提交,会发生什么?
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:
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?
简而言之:我认为这是不可能的,但是
您可以做的是在 Database 类上设置一个默认值“false”的标志(这不好),并在 using 块内的最后一行调用一个设置它的方法设置为“true”,然后在 Dispose() 方法中您可以检查标志是否“有异常”。
和数据库类
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.
And the database class
听起来你需要
TransactionScope
http://msdn.microsoft.com/en-us/库/system.transactions.transactionscope.aspx
Sound like you need
TransactionScope
http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx
您应该将 using 块的内容包装在 try/catch 中,并回滚 catch 块中的事务:
You should wrap the contents of your using block in a try/catch and roll back the transaction in the catch block:
正如安东尼上面指出的,问题是在这种情况下使用 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.
您可以从 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.