检查线程关联性的代码契约 - 好主意吗?

发布于 2024-10-29 20:48:37 字数 279 浏览 1 评论 0原文

我正在尝试学习代码契约并了解它们有什么用处。

我有一个 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 技术交流群。

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

发布评论

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

评论(3

子栖 2024-11-05 20:48:37

您的合同应该与您的代码有关。 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.

尐籹人 2024-11-05 20:48:37

我认为你想要进行这些亲和力检查是正确的。它们是尽早发现细微错误的好方法,但不能像 Henkdecyclone 提到的那样使用代码契约静态检查。

我有一个名为 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 method Ensure.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.

自控 2024-11-05 20:48:37

方法的契约是“对于特定的有效输入,给定的方法将产生有效的输出”。

就您而言,您没有验证方法的输入。这就是为什么我不建议使用这种方法。

换句话说,这不是合同,而只是某种验证/断言。

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.

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