Mutex
The preceding code works well for a single instance application since tasks run inside a process and the lock actually locks a memory barrier inside the process. If we run multiple instances of the application, both applications will have their own copy of the static data members and will, therefore, lock their own memory barriers. This will allow one thread per process to actually enter the critical section and try to write the file. This causes the following System.IO.IOException: 'The process cannot access the file …\test.txt' because it is being used by another process.'.
To be able to apply locks to shared resources, we can apply a lock at the kernel level using the mutex class. Like lock, mutex allows only one thread to access ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access