Method lock in c#

后端 未结 4 1980
孤城傲影
孤城傲影 2021-02-19 05:16

I have one class with these three methods. This class is used by many threads. I would like the Method1 to wait, if Method2 and/or Method3 are running in any threads. Any sugges

4条回答
  •  灰色年华
    2021-02-19 05:36

    I would suggest a ReaderWriterLockSlim (http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx)

    Similar to read operations, Method 2 and Method3 may occur in parallel, while Method1 (like a write operation) would need to wait for those to finish. It's not the regular read/write concurrency situation, but the logic is similar.

    public class Class1
    {
        private ReaderWriterLockSlim methodLock = new ReaderWriterLockSlim();
        public static void Method1() 
        {
            methodLock.EnterWriteLock();
            try
            {
                //Body function
            }
            finally
            {
                methodLock.ExitWriteLock();
            }
        }
    
        public static void Method2() 
        {
             methodLock.EnterReadLock();
            try
            {
                //Body function
            }
            finally
            {
                methodLock.ExitReadLock();
            }
        }
    
        public static void Method3() 
        {
             methodLock.EnterReadLock();
            try
            {
                //Body function
            }
            finally
            {
                methodLock.ExitReadLock();
            }
        }
    }
    

提交回复
热议问题