1

I am pretty new to C# and wanted to save some settings. My application has to be able to run multiple instances therefore it is a possibility of several simultaneous writes to the user.config file. Causing the config file to become corrupted. Therefore I wonder if there are any File level locking when they are saved.

Tried to take a look on the source code for .Save and this seems to be boiling down to the interface call IInternalConfigHost.OpenStreamForWriting. But it is an interface so I can not easily answer this question on my own.

Updated the wording somewhat.

Basically I am wondering if the user.config file can become corrupt due to several simultaneous writes to it from several instances of my application.

Jerry
  • 13
  • 5
  • not sure if I got your question right... several instances reading from one file is no problem at all, but only one can have write access at a time. – Breeze Apr 04 '16 at 10:26
  • Oh sorry, you pretty much answered my question. Thought several program could have write access at one time. – Jerry Apr 04 '16 at 10:48

2 Answers2

1

If two or more instances of your program try to write to the same configuration file, you will get exceptions while calling .Save

What you can do is use the Mutex Class to synchronize access from multiple instances. You can check this answer on how to do it properly.

However, one thing that you need to think about is : if one of your instances updates the configuration file, should the others be notified and reload it to provide a consistent behaviour?

afewcc
  • 1,077
  • 3
  • 9
  • 20
  • This is the answer since it solves file write problem. As for notifying updates. Yes I need that to. However that's a different talk. – Jerry Apr 05 '16 at 12:06
0

You can use mutex lock object. It is prevents simulataneouse access to shared object bewtween multi thread and multi process.

Reference following page. http://derpturkey.com/c-cross-process-synchronization/