I am writing a cataloging application that parses through and extracts information from files and stores the information from each file in an object instance. In addition to the data extracted from the file the objects also have additional meta data properties (author, tags, notes, etc..) which later get stored in a separate XML file.
Extracting the data from the files is a time consuming process so I have it running on a separate thread. The properties extracted from the files will only ever come from the files, and thus have [ReadOnly] attributes to prevent the user from editing them. The meta data properties on the other hand are only populated by the user and thus are not read only. I'm allowing the user to view/edit these object through a PropertyGrid.
So if the extraction process is running on one thread populating the file properties of an object, is there any danger in letting the user edit the meta data prop开发者_StackOverflowerties at the same time? I'm trying to decided if I should use a modal interface that prevents the user from doing anything until the extraction is complete/canceled, or a non-modal interface that allows them to continue working while the extraction is running.
To be specific to your question: No there is no problem.
What you should watch out for is that your properties written by the background thread are not read from the UI thread while they are being written. If you can't guarantee this, you must either use locks, marshall the write to the UI thread. (using control.Invoke()
or BackgroundWorker
or, make sure the write is an atomic write of pointer to an object that is not edited by the background thread while visible from the UI thread. I would not assume standard containers like List<T>
are thread safe.
[wording changed]
In general, if the properties do not reference shared state, then they may be updated on separate threads with no trouble, even if they are part of the same object.
You are free to do it, only if you are sure that the change of one property doesn't cause the change of the other that may be changed in another thread. Shortly if the properties don't have shared data, that will work great!
Assuming "normal" properties - eg., auto-implemented or simple field-backed:
public class MyClass {
[ReadOnly]
public string FileAuthor { get; set; }
public string MetaDataAuthor {
get { return _metaDataAuthor; }
set { _metaDataAuthor = value; }
}
private string _metaDataAuthor;
}
There shouldn't be any issues related to changing the values on different threads. It's not necessary to synchronize writing to different variables.
However - if the PropertyGrid is showing the file properties (like FileAuthor) - you'd probably want to synchronize the reading (binding the PropertyGrid) and writing (the file extract) of those.
精彩评论