gpt4 book ai didi

vb.net - 在 VB.NET 中使用 XML API 时的线程安全

转载 作者:行者123 更新时间:2023-12-03 00:30:13 24 4
gpt4 key购买 nike

我有一个关于在 VB.NET 中使用 XML 的线程安全性的问题。

我有一个应用程序,它在用户创建新项目/对现有项目进行更改时管理 XmlDocument 对象。我已经知道我需要同步对 XmlDocument.CreateElement(...) 的调用。我的问题是,我可以继续构建返回的元素而不同步,然后在将该元素附加到 XmlDocument 时再次同步吗?

这就是我认为我可以做的,我只需要确保它是线程安全的,就像我认为的那样:

' "doc" object already exists as an XmlDocument
SyncLock doc
Dim newsub As XmlElement = doc.CreateElement("submission")
End SyncLock

' use "newsub" here without synchronization

SyncLock doc
doc.Item("submissions").AppendChild(newsub)
End SyncLock

当添加“newsub”的子元素时,我也会仅在创建每个元素时同步。

作为这个问题的后续,我最好同步“newsub”对象的整个构建吗?我认为像上面这样做更好的原因是为了性能,但我无论如何都不是专家,不知道我是否真的对性能产生了有意义的影响,或者只是让事情变得复杂。

最佳答案

一般来说,当使用从 XmlNode 派生的任何类时,您将需要同步,因为它的文档明确指出:

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

这意味着您在附加子项时需要同步,如您所示。

As a followup to this question, would I be better off just synchronizing the entire building of the "newsub" object? The reason I think doing it like above is better is for performance, but I am not by any means an expert in whether I am actually making a meaningful impact on performance, or just complicating things.

这取决于 - 如果您要做任何可能导致它可以从多个线程使用的事情,那么您可能需要同步它。

在上面的代码中,在同步之外使用 newsub 应该是安全的,因为在将其作为子项附加之前,它不是实际文档树的一部分。这将减少 doc 被锁定的时间,如果从多个线程使用 doc,这可以减少争用。

关于vb.net - 在 VB.NET 中使用 XML API 时的线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16675250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com