In php, it is possible to simultaneously access a file with locks for writing LOCK_EX (exclusive write access) and for reading LOCK_SH (general access for reading) The lock is called after opening the file through a flock
When a lock is called, the behavior depends on the type of lock. In general, it works similarly to ReaderWriterLock and in c # you need to use it for this behavior. However, ReaderWriterLock in c # works within one process (and does not relate directly to files).
Moreover, windows will interfere with simultaneous access to the file from different processes.
In c # there is FileShare, but it seems that this is just allowing another process to open the file for the same type of access (from msdn it’s not very clear what it really is)
Give an example of how to make the same blocking behavior with a common file in c # as in php or its abstract equivalent ReaderWriterLock
upd : I see an explanation is required what kind of behavior is expected; let's say there are several processes that almost simultaneously want
- to read
- to read
- to read
- write
- to read
- write
The first 3 will receive permission for simultaneous reading. The 4th waits and receives a block for recording when the first 3 release the file. The 5th will wait until the 4th releases, and the 6th will not release the 5th
So, the FileShare.ReadWrite or FileShare.Write options are not honored (I checked 2 writers and I have porridge in the output). They merely indicate what the other process can do without throwing an exception. But do not protect files from simultaneous recording.
If you put an exclusive lock without FileShare, then other processes will receive exceptions, which we want to avoid
upd2: and again no one understands what the problem is.
Problem : many processes that can read and write to a file.
Purpose : to protect the general file from concurrent access so that only one writer could write at a time. Not “deny access to others”, but provide competing access when many readers can read a lot at once, but write only one, that is, what ReaderWriterLock is for (I don’t see any fundamental difference between it and the file blocking system in php)
The option "catch exceptions and repeat after 100ms to the victorious" does not hold water. A writer who waits until the file is free may never wait, because in these 100ms a lot of readers can open the file for themselves. The correct solution is that the read / write lock is put in a queue and in php (and not only in it) it is available out of the box, but in c # I have not found how it is done.
In short, the question is: how to make a ReaderWriterLock for files that go between several processes?