Let's say we have a file - the one to be used with multiple processes.
I start with an assumption that file gets Write locked to get changed. If that is not the case for you, then my approach will not work. So if it sounds reasonable for you, then see the solution.
public static void Lock(string path, Action<FileStream> action)
{
var autoResetEvent = new AutoResetEvent(false);
while(true)
{
try
{
using (var file = File.Open(path,
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.Write))
{
action(file);
break;
}
}
catch (IOException)
{
var fileSystemWatcher =
new FileSystemWatcher(Path.GetDirectoryName(path))
{
EnableRaisingEvents = true
};
fileSystemWatcher.Changed +=
(o, e) =>
{
if(Path.GetFullPath(e.FullPath) == Path.GetFullPath(path))
{
autoResetEvent.Set();
}
};
autoResetEvent.WaitOne();
}
}
}
So as you can see, we do an infinite loop which exits only on non
IOException
or when the block finishes successfully.
To wait and not consume 100% CPU
AutoResetEvent
which gets Set by
FileSystemWatcher.Changed
event.
So the flow looks like that:
1) We try to open the file
2) If we have an IOException, we wait until the file gets changed
3) We try to open file again, if failed - wait again
4) If file opened successfully, we perform an action passed as a parameter
You should carefully handle
IOException
inside your action. See the example:
FileLocker.Lock(@"c:\file",
(f) =>
{
try
{
f.Write(buf, 0, buf.Length);
}
catch(IOException ioe)
{
}
});
If you have any ideas on how to improve the solution, feel free to comment.