我有一份读写的文件。 我需要确保在写给它时,没有人会试图给它写信。
I put a lock on the whole function which allows to either read or write but I still get errors such as The process cannot access the file FILENAME because it is being used by another process.
public static TYPE Property{
get{
data mydata;
Object obj = new object();
Monitor.Enter(obj);
// check if data has not changed
// if it has not, just read
using (Stream stream = File.Open(fileLocation, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
//....
}
// else, if data changed, then need to write to file to save the new data
using (Stream stream = File.Open(fileLocation, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read)) {
BinaryFormatter bf = new BinaryFormatter();
try {
bf.Serialize(stream, (data);
}
//DONE processing
Monitor.Pulse(obj);
Monitor.Exit(obj);
return data
}