locked
ReaderWriterLock.AcquireReaderLock doesn`t work. RRS feed

  • Question

  • I have this sample:

        public class MyResource  
        {  
            ReaderWriterLock rwl = new ReaderWriterLock();  
     
            public void Read(int id)  
            {  
                rwl.AcquireReaderLock(Timeout.Infinite);              
                try 
                {  
                    Console.WriteLine(id.ToString());  
                    if (id == 1)   
                        Thread.Sleep(5000);  
                }  
                finally { rwl.ReleaseReaderLock(); }  
            }  
        } 

    when I call:
        class Program  
        {  
            public static MyResource res = new MyResource();  
            static void Main(string[] args)  
            {  
                Thread t = new Thread(MyMethod);  
                t.Start(1);  
                Thread t1 = new Thread(MyMethod);  
                t1.Start(2);  
                Console.ReadKey();  
            }  
     
            static void MyMethod(object id)  
            {  
                res.Read(Convert.ToInt32(id));  
            }  
        } 

    I have on the console immediatelly  1 and 2. I thought that the 2 should be displayed after 5 seconds.
    It looks like the lock doesn`t work.
    Why is 2 displayed immediatelly?
    Sunday, January 4, 2009 3:13 PM

Answers

  • Review the docs for ReaderWriterLock.  It doesn't work the way you think it does.  It is designed to allow multiple readers and one writer.  Only a write lock blocks a reader.  To get what you want, you'll need a plain lock:

        public class MyResource {
          object locker = new object();

          public void Read(int id) {
            lock (locker) {
              Console.WriteLine(id.ToString());
              if (id == 1)
                Thread.Sleep(5000);
            }
          }
        }


    Hans Passant.
    • Marked as answer by kicaj Sunday, January 4, 2009 10:24 PM
    Sunday, January 4, 2009 4:01 PM