Access single file from different threads or processes and maintain consistensy without using extra locks
Sometimes you want to access a single file from different processes or threads and maintain its consistency. The example may be a common database or just a counter. When the file is opened in read-only mode, the question is trivial. But what if you want to write from different threads? Here is the code sample. The idea is to use File.Open constructor with the FileShare.None option. This option allows only one thread to access the file (either for reading or writing) and deny all other threads. The other threads should catch IOException and try to access the file subsequently with a random delay.