ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim(); // Acquire read lock and read data from shared resource rwLock.EnterReadLock(); // Read data here rwLock.ExitReadLock(); // Acquire write lock and write data to shared resource rwLock.EnterWriteLock(); // Write data here rwLock.ExitWriteLock();
static ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim(); // Method that performs read operation on shared resource static void ReadData() { rwLock.EnterReadLock(); try { // Read data from shared resource here } finally { rwLock.ExitReadLock(); } } // Method that performs write operation on shared resource static void WriteData() { rwLock.EnterWriteLock(); try { // Write data to shared resource here } finally { rwLock.ExitWriteLock(); } }In this example, we define two methods that perform read and write operations on a shared resource. The ReaderWriterLockSlim instance is created as a static field, and is used to synchronize access to the shared resource in both methods. The try-finally block is used to ensure that the lock is released even if an exception is raised. Package library: System.Threading.