我有一个可以读写的文件。我需要确保它何时被写入,没有其他人会尝试写入它。
我锁定了允许读取或写入的整个函数,但我仍然遇到错误,例如进程无法访问文件“文件名”,因为它正在被另一个进程使用。
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
}