C# 如何单元测试/验证类提供的 API 是否是线程安全的?
我需要将它放在多线程上下文中吗?或者只要类的成员不公开为共享资源并且是不可变的和只读的,就应该证明这一点。
Do I need to put it under a multithread context? Or as long as the members of the class don't expose as shared resources and are immutable and readonly, that should proves it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
api 中的大多数实例方法根本不应该是线程安全的。客户端代码应根据上下文决定是否同步访问以及以何种粒度同步访问。只有静态(类)方法才能提供线程安全性,并且它不应该是强制性的。
为了回答您的问题,我认为没有一种简单的、不依赖于上下文的方法来测试线程问题。线程问题,例如数据争用或死锁,大多数时候很难发现:概率低、非常依赖输入数据、不确定性等。
Most instance methods in your api shouldn't be thread safe at all. Client code should decide -- depending on context -- whether to synchronize access or not, and at which granularity. Only static (class) methods would provide thread-safety and it shouldn't be mandatory.
To answer your question, I don't think there is a trivial non-context-dependent way for testing threading issues. Threading problems, such as data-races or deadlocks, are most of the time very hard-to-find: low probability, very dependent on input data, non deterministic etc.