I want to implement a thread safety list, but thread safety should be ensured on the entire block of operations not only on one operation (for example, add, delete, etc.). A usage example should look like this:
list.Lock(); list.Add(sth); list.RemoveAt(4); list.Unlock();
I want the list to require locking for any operations. For instance:
list.Add(sth);
called without preliminary blocking should result in an exception. This is why I do not use the lock() operator - checking for locks is critical to this solution.
Implementing such a list using Monitor is not a difficult task - but only until you want to check whether the list is locked or not. I thought of the following scenario:
// Inside list class private object lockObject; private bool locked; public void Lock() { Monitor.Enter(lockObject); locked = true; } public void Unlock() { Monitor.Exit(lockObject); locked = false; }
Unfortunately, this code is subject to race conditions - regardless of whether it is locked before or after entering or exiting a critical section.
Another approach related to the use of TryEnter, but this method is really included in the critical section if no lock is obtained, which can also lead to race conditions.
How should I implement this mechanism to ensure thread safety and how to avoid race conditions while checking if the list is locked or not?
source share