I have a file that is read and written to. I need to make sure when its been written to, nobody else will try to write to it.
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
}
You’re creating a new monitor to lock on every time the property is invoked. You need to lock on the same monitor otherwise there’s no point in locking at all.
You should also just use a “lock” statement – you’re never waiting, so there’s no point in pulsing. Currently, if any exceptions are thrown, you’ll end up “leaking” the lock. That would normally be a really bad problem, but as you’re not reusing the lock anyway, that’s masking the issue.
For example:
As an aside, this looks like it’s doing more work than I’d really expect in a property. Are you sure a method wouldn’t make more sense?