简体   繁体   中英

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. 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.

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

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. 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).

In this scenario is it acceptable to use locking directly on the XObject itself for thread safety, or is there an alternaitve?

I would not recommend locking on the XObject itself. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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