检查线程关联性的代码契约 - 好主意吗?
我正在尝试学习代码契约并了解它们有什么用处。
我有一个 WPF 应用程序,因此很多代码必然只在 UI 线程上运行。相当多的实用程序类期望仅从 UI 线程调用。
在我的代码中加入这些是个好主意吗?为什么是/不是?
Contract.Requires(Thread.CurrentThread == Application.Current.Dispatcher.Thread);
静态检查器能够可靠地检查这些吗?
感谢您的任何意见!
I'm trying to learn Code Contracts and get an idea of for what are they useful.
I have a WPF application, so a lot of code is bound to run exclusively on the UI thread. Quite a few utility classes expect to be called from the UI thread only.
Is it good idea so sprinkle these through my code? Why yes/not?
Contract.Requires(Thread.CurrentThread == Application.Current.Dispatcher.Thread);
Will the static checker be able to reliably check these?
Thanks for any input!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的合同应该与您的代码有关。 Dispatcher 和 Thread 类不是您的,它们不受自己的合约保护。
所以不,静态检查器根本无法检查这一点。
运行时检查可能会起作用,但它们对库中已内置的调试检查几乎没有什么帮助。
Your contracts should be about your code. The Dispatcher and Thread classes aren't yours and they're not guarded by contracts of their own.
So No, the static checker won't be able to check this at all.
The runtime checks might work but they add little to the Debug checks already built into the library.
我认为你想要进行这些亲和力检查是正确的。它们是尽早发现细微错误的好方法,但不能像 Henk 和 decyclone 提到的那样使用代码契约静态检查。
我有一个名为
Ensure
的静态类,其方法Ensure.OnUiThread()
包含与您提到的完全相同的检查。我用[Conditional("DEBUG")]
标记它,以免减慢/膨胀生产代码。对我来说效果很好。I think you are right to want to make these affinity checks. They are a great way to spot subtle bugs early but not something that can be checked statically using code contracts as mentions by Henk and decyclone.
I have a static class called
Ensure
with a methodEnsure.OnUiThread()
that contains the exact same check as you mention. I mark this with[Conditional("DEBUG")]
so as not to slow/bloat production code. Works nicely for me.方法的契约是“对于特定的有效输入,给定的方法将产生有效的输出”。
就您而言,您没有验证方法的输入。这就是为什么我不建议使用这种方法。
换句话说,这不是合同,而只是某种验证/断言。
A contract for a method is "for a specific valid input, given method will produce a valid output".
In your case, you are not validating the Input of your method. That is why I would not recommend using this approach.
In other words, this would not be a contract but just some sort of validation/assertion.