Question

I have an application which runs multiple process at the same time for reading and writing to file.

private Process PrepareProcess(string workingDirName, string scriptPath, string[] args) {
        var process = new Process {
            StartInfo = {
                WorkingDirectory = workingDirName,
                FileName = scriptPath,
                Arguments = string.Format(string.Join(" ", args))
            }
        };
        return process;
    }

I need to be sure that file will be modified only by one proccess at the same time. How to do that?

The process will run external script which will modify file. I can't manage of how to open file. I need to manage running process.

Thanks!

Was it helpful?

Solution

You can use "Named Mutex". It helps you to say "Hey wait, am working on with that file!". It is your call you can wait or ignore that file.

Take a look at Mutex class

Also worth noting that by default if you open a file, FileShare will be None which means don't share access with anyone till I close the file. So it will fail when attempt to access in another process. You can't modify it simultaneously. To prevent that failure and handling exception and all using "Mutex" is a elegant way.

OTHER TIPS

Pass FileShare.None to File.Open when you open the file.

That will block any attempts for multiple processes to write to the file simulataneously. The downside is that if a process attempts to open the file when another process already has it open, then the second attempt will fail. If that's a problem then you will probably need to use a mutex to serialize access. The advantage of using a mutex is that it allows the second process to block and wait until the file is available.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top