简体   繁体   English

锁定/线程安全访问XObject

[英]Locking on / thread safe access to XObject

I am writing a GUI application that is based around reading & editing a large, fairly complex (multiple document) XML structure. 我正在编写一个GUI应用程序,该应用程序基于读取和编辑大型的,相当复杂的(多个文档)XML结构。 The GUI itself is largely based on databinding and so most of the interaction with the XML will be done on the UI thread through an object-based model which under the covers uses LINQ to XML, however I know that some operations (such as searching and loading) will need to be performed on a background thread and so I need to ensure that we are accessing this XML in a thread-safe way. GUI本身主要基于数据绑定,因此与XML的大多数交互将通过基于对象的模型在UI线程上完成,该模型在后台使用LINQ to XML,但是我知道某些操作(例如搜索和加载)将需要在后台线程上执行,因此我需要确保我们以线程安全的方式访问此XML。

Its easy enough for me to ensure that all editing of the XML is thread-safe (eg with global locks or by performing all edits on the UI thread), however I notice that the documentation for XObject states 确保我对XML的所有编辑都是线程安全的(例如,使用全局锁或通过对UI线程执行所有编辑)很容易,但是我注意到XObject的文档指出

Any public static members of this type are thread safe. 此类型的任何公共静态成员都是线程安全的。 Any instance members are not guaranteed to be thread safe. 不保证任何实例成员都是线程安全的。

Which means I must synchronise all access to any XObject instances used in my application. 这意味着我必须同步对应用程序中使用的任何 XObject实例的所有访问。 Unfortunately because of the way that my object model operates it is difficult for me to ensure that at most 1 instance of any object in my model has access to any given XObject , which means that I can't ensure thread safety by locking on private objects (normally best practice to prevent deadlocks). 不幸的是,由于对象模型的运行方式,我很难确保模型中任何对象的最多1个实例可以访问任何给定的XObject ,这意味着我无法通过锁定私有对象来确保线程安全(通常是防止死锁的最佳实践)。

In this scenario is it acceptable to use locking directly on the XObject itself for thread safety, or is there an alternaitve? 在这种情况下,可以直接在XObject本身上使用锁定来保证线程安全,还是可以替代的?

I would not recommend locking on the XObject itself. 我不建议锁定XObject本身。 It might work, but it's generally not a good solution (since anybody can do that). 它可能有效,但是通常不是一个好的解决方案(因为任何人都可以这样做)。 What you can do instead is add a private annotation onto the XObject and lock on that. 相反,您可以做的是在XObject上添加私有注释并对其进行锁定。 You make the annotation private by using an object of a type which is only accessible to you (so internal to your assembly). 您可以通过使用只能由您自己访问的类型的对象(因此在程序集内部)来使注释私有。 Since to lookup an annotation one needs to know its type, if the type is "private" nobody else can look it up. 由于要查找注释,因此需要知道其类型,如果该类型为“私有”,则其他任何人都无法查找它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM