XElement的add操作线程安全吗?
通过 ADD 方法以并行方式(如并行 foreach)将子元素添加到 XElement 是否安全?
谢谢!
Is it safe to Add child elements to an XElement via its ADD method in a parallel way (as in a parallel foreach)?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自文档:
换句话说,不,add 方法不是线程安全的。
From the documentation:
In other words, no, the
add
method is not thread safe.最近(痛苦的)经历让我认为线程非常非常不安全。
我分析了几个转储文件,其中分别包含 740 万个和 880 万个额外不需要的 XElement 实例。据我所知,它们是在两个线程池线程同时调用一些涉及操作 XElement 子节点(包括在某些情况下调用 Add())的看似无害的代码时创建的。
这并不奇怪 - XElement 和关联的类是使用类似链接列表的结构实现的,如果您打乱链接引用,可能会出现各种奇怪的结果 - 循环、未附加的片段等。
Recent (painful) experience leads me to think that it is very, VERY thread un-safe.
I analyzed a couple of dump files that contained 7.4 million and 8.8 million extra unwanted XElement instances respectively. As best I can determine, they got created when some innocuous-looking code involving manipulating the sub-nodes of an XElement (including calling Add() in some cases) got called from two thread pool threads at the same time.
This isn't too surprising - XElement and the associated classes are implemented using linked-list-like structures, and if you scramble the link references a variety of weird results can ensue - loops, unattached fragments, etc.