Example #1
0
 /// <summary>
 /// Initializes a new instance of Row.
 /// </summary>
 public Row()
 {
     //The row's status is true
     Status = true;
     //Assign it's lock
     Lock = new ReadWriteLock();
 }
Example #2
0
        public FirstLevelCacheManager()
        {
            ReadWriteLock rwLock = new ReadWriteLock();

            unboundReadLock  = rwLock.ReadLock;
            unboundWriteLock = rwLock.WriteLock;
        }
Example #3
0
        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
            if (!this.IsDisposed)
            {
                this.IsDisposed = true;
                var _dic = this.m_dic;
                var _readerWriterLock = this.m_readWriteLock;

                this.m_dic           = null;
                this.m_readWriteLock = null;

                try { if (this.m_dic != null)
                      {
                          this.m_dic.Clear();
                      }
                }
                catch { }
                try { if (this.m_readWriteLock != null)
                      {
                          this.m_readWriteLock.Dispose();
                      }
                }
                catch { }
            }
        }
Example #4
0
        public EventListenerRegistry()
        {
            ReadWriteLock listenersRwLock = new ReadWriteLock();

            listenersReadLock  = listenersRwLock.ReadLock;
            listenersWriteLock = listenersRwLock.WriteLock;
        }
Example #5
0
        public void MultipleReadersAtTheTime()
        {
            var w = new ManualResetEvent(false);
            var x = new ReadWriteLock();

            int[] z       = { 0 };
            var   threads = new Thread[5];

            for (int index = 0; index < 5; index++)
            {
                threads[index] = new Thread
                                 (
                    () =>
                {
                    w.WaitOne();
                    using (x.EnterRead())
                    {
                        Interlocked.Increment(ref z[0]);
                        Thread.Sleep(10);
                    }
                }
                                 );
            }
            for (int index = 0; index < 5; index++)
            {
                threads[index].Start();
            }
            w.Set();
            for (int index = 0; index < 5; index++)
            {
                threads[index].Join();
            }
            Assert.AreEqual(6, Interlocked.Increment(ref z[0]));
        }
Example #6
0
        public XmlTypeRegistry()
        {
            ReadWriteLock rwLock = new ReadWriteLock();

            readLock  = rwLock.ReadLock;
            writeLock = rwLock.WriteLock;
        }
        public void TestReadWriteLock_MultipleWrites()
        {
            var rwlock = new ReadWriteLock();
            var random = new Random();
            int value = 0;

            Action action = () =>
            {
                using (rwlock.EnterWriteScope())
                {
                    var v = value;
                    Thread.Sleep(random.Next(10));
                    var tmp = v + 100;
                    Thread.Sleep(random.Next(10));
                    value = tmp;
                }
            };

            var tasks = Enumerable.Range(1, 100)
                .Select(i => Task.Factory.StartNew(action))
                .ToArray();

            Task.WaitAll(tasks);

            const int expected = 100 * 100;

            Assert.AreEqual(expected, value);
        }
 private CourseInfo()
 {
     CourseCodeToCourse = new OptionalDictionary <string, CourseModel>();
     CourseNameToCourse = new OptionalDictionary <string, CourseModel>();
     CourseCodes        = new HashSet <string>();
     Lock = new ReadWriteLock();
 }
Example #9
0
 public void CanEnterWriteEx()
 {
     using (var x = new ReadWriteLock())
     {
         IDisposable engagement = null;
         try
         {
             if (x.TryEnterWrite(out engagement))
             {
                 Assert.IsTrue(x.IsCurrentThreadWriter);
             }
             else
             {
                 Assert.Fail();
             }
         }
         finally
         {
             if (engagement != null)
             {
                 engagement.Dispose();
             }
         }
     }
 }
Example #10
0
 public void CanKnowIsWriter()
 {
     // ReadWriteLock always able to tell if a therad is the writer
     using (var x = new ReadWriteLock(true))
     {
         Assert.IsFalse(x.HasWriter);
         using (x.EnterWrite())
         {
             Assert.IsTrue(x.IsCurrentThreadWriter);
             Assert.IsTrue(x.HasWriter);
         }
         // Not Reentrant ReadWriteLock is not
         using (var y = new ReadWriteLock(false))
         {
             Assert.IsFalse(y.HasWriter);
             using (y.EnterWrite())
             {
                 Assert.IsTrue(y.IsCurrentThreadWriter);
                 Assert.IsTrue(y.HasWriter);
             }
             // ReadWriteLock is not reentrant by default
             using (var z = new ReadWriteLock())
             {
                 Assert.IsFalse(z.HasWriter);
                 using (z.EnterWrite())
                 {
                     Assert.IsTrue(z.IsCurrentThreadWriter);
                     Assert.IsTrue(z.HasWriter);
                 }
             }
         }
     }
 }
Example #11
0
 public void CanKnowIsReader()
 {
     // Reentrant ReadWriteLock is able to tell if a therad is a reader
     using (var x = new ReadWriteLock(true))
     {
         Assert.IsFalse(x.HasReader);
         using (x.EnterRead())
         {
             Assert.IsTrue(x.IsCurrentThreadReader);
             Assert.IsTrue(x.HasReader);
         }
         // Not Reentrant ReadWriteLock is not
         using (var y = new ReadWriteLock(false))
         {
             Assert.IsFalse(y.HasReader);
             using (y.EnterRead())
             {
                 Assert.Throws(typeof(NotSupportedException), () => GC.KeepAlive(y.IsCurrentThreadReader));
                 Assert.IsTrue(y.HasReader);
             }
             // ReadWriteLock is not reentrant by default
             using (var z = new ReadWriteLock())
             {
                 Assert.IsFalse(z.HasReader);
                 using (z.EnterRead())
                 {
                     Assert.Throws(typeof(NotSupportedException), () => GC.KeepAlive(z.IsCurrentThreadReader));
                     Assert.IsTrue(z.HasReader);
                 }
             }
         }
     }
 }
        private int GetInsertCollectionIndex(TreeListViewItem item)
        {
            int index = -1;

            ReadWriteLock.AcquireReaderLock(-1);
            if (!this.Contains(item))
            {
                switch (SortOrder)
                {
                // No sortorder -> at the end of the collection
                case System.Windows.Forms.SortOrder.None:
                    index = this.Count;
                    break;

                default:
                    for (int i = 0; i < this.Count; i++)
                    {
                        // Change the index for the compare if the order is descending
                        int indexcompare = i;
                        //                SortOrder == System.Windows.Forms.SortOrder.Ascending ?
                        //              i : this.Count - (1 + i);
                        int comp = Comparer.Compare(item, this[indexcompare]);
                        if (comp <= 0)
                        {
                            index = indexcompare;
                            break;
                        }
                    }
                    index = index == -1 ? this.Count : index;
                    break;
                }
            }
            ReadWriteLock.ReleaseReaderLock();
            return(index);
        }
Example #13
0
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configFile">配置文件</param>
        /// <param name="isEnabledAop">是否使用Aop</param>
        public IocContainer(string configFile, bool isEnabledAop)
        {
            if (!string.IsNullOrEmpty(configFile))
            {
                string filePath = PathUtils.GetFileFullPath(configFile);
                if (!File.Exists(filePath))
                {
                    throw new FileNotFoundException(configFile + " not found!", configFile);
                }
            }

            this.m_defaultAssembly = null;
            this.m_rwLock          = new ReadWriteLock();
            this.m_dicType         = new Dictionary <Type, List <Type> >();

            if (isEnabledAop)
            {
                this.m_aopProxy = new AopProxy();
            }

            if (!string.IsNullOrEmpty(configFile))
            {
                this.Load(configFile);
            }
        }
    static public int Main(String[] args)
    {
        const int READER_COUNT = 4;
        const int WRITER_COUNT = 4;

        Thread[]      thrdReaders = new Thread[READER_COUNT];
        Thread[]      thrdWriters = new Thread[WRITER_COUNT];
        ReadWriteLock XYZ         = new ReadWriteLock( );

        XYZ.OutX   = 0;
        XYZ.ReadX  = 0;
        XYZ.WriteX = 10;
        ThreadStart reader = new ThreadStart(XYZ.ReaderFunc);
        ThreadStart writer = new ThreadStart(XYZ.WriterFunc);

        for (int i = 0; i < READER_COUNT; i++)
        {
            thrdReaders[i] = new Thread(reader);
            thrdReaders[i].Start( );
        }
        for (int i = 0; i < WRITER_COUNT; i++)
        {
            thrdWriters[i] = new Thread(writer);
            thrdWriters[i].Start( );
        }
        for (int i = 0; i < READER_COUNT; i++)
        {
            thrdReaders[i].Join();
        }
        for (int i = 0; i < WRITER_COUNT; i++)
        {
            thrdWriters[i].Join();
        }
        return(failed);
    }
Example #15
0
        public CacheServiceMock()
        {
            ReadWriteLock rwLock = new ReadWriteLock();

            readLock  = rwLock.ReadLock;
            writeLock = rwLock.WriteLock;
        }
Example #16
0
        public void ReentryReadToWriteCheck()
        {
            var         w            = new ManualResetEvent(false);
            var         x            = new ReadWriteLock();
            var         enterCount   = 0;
            var         doneCount    = 0;
            var         errorCount   = 0;
            var         successCount = 0;
            ThreadStart tmp          = () =>
            {
                using (x.EnterRead())
                {
                    Interlocked.Increment(ref enterCount);
                    w.WaitOne();
                    // If a thread is a reader it can become a writer as long as there are no other readers
                    // When we have multiple readers trying to become a writer...
                    IDisposable engagement = null;
                    try
                    {
                        // Write mode is not requested - there are other readers which we don't wait to leave
                        if (x.TryEnterWrite(out engagement))
                        {
                            Interlocked.Increment(ref successCount);
                        }
                        else
                        {
                            Interlocked.Increment(ref errorCount);
                        }
                    }
                    finally
                    {
                        if (engagement != null)
                        {
                            engagement.Dispose();
                        }
                    }
                }
                Interlocked.Increment(ref doneCount);
            };
            var threads = new Thread[5];

            for (int index = 0; index < 5; index++)
            {
                threads[index] = new Thread(tmp);
            }
            for (int index = 0; index < 5; index++)
            {
                threads[index].Start();
            }
            Thread.Sleep(10);
            Assert.AreEqual(5, enterCount);
            w.Set();
            for (int index = 0; index < 5; index++)
            {
                threads[index].Join();
            }
            Assert.AreEqual(5, doneCount);
            Assert.AreEqual(0, successCount); // None succeds
            Assert.AreEqual(5, errorCount);   // All fail
        }
Example #17
0
        public AnnotationCache()
        {
            ReadWriteLock rwLock = new ReadWriteLock();

            readLock  = rwLock.ReadLock;
            writeLock = rwLock.WriteLock;
        }
 private DepartmentInfo()
 {
     IdToDepartment   = new OptionalDictionary <int, DepartmentModel>();
     NameToDepartment = new OptionalDictionary <string, DepartmentModel>();
     DeptIds          = new HashSet <int>();
     Lock             = new ReadWriteLock();
 }
Example #19
0
        /// <summary>
        /// 构造函数
        /// </summary>
        public AopProxy()
        {
            this.m_classId    = GetGlobalId();
            this.m_moduleName = "Afx.Aop.Dynamic" + GetGlobalId();

            var assemblyName = new AssemblyName(this.m_moduleName);

            assemblyName.Version = new Version(1, 0, 0, 0);
#if NETCOREAPP || NETSTANDARD
            this.m_assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, this.m_assemblyBuilderAccess);
            this.m_moduleBuilder   = this.m_assemblyBuilder.DefineDynamicModule(this.m_moduleName);
#else
            this.m_assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, this.m_assemblyBuilderAccess);
            if (this.m_assemblyBuilderAccess == AssemblyBuilderAccess.RunAndSave)
            {
                this.m_moduleBuilder = this.m_assemblyBuilder.DefineDynamicModule(this.m_moduleName, this.m_moduleName + ".dll");
            }
            else
            {
                this.m_moduleBuilder = this.m_assemblyBuilder.DefineDynamicModule(this.m_moduleName);
            }
#endif
            this.m_rwLock       = new ReadWriteLock();
            this.m_proxyTypeDic = new Dictionary <Type, Type>();
        }
Example #20
0
        public RevertChangesHelper()
        {
            ReadWriteLock rwLock = new ReadWriteLock();

            readLock  = rwLock.ReadLock;
            writeLock = rwLock.WriteLock;
        }
Example #21
0
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="xmlFile">配置文件路径</param>
        /// <param name="enabledChangedEvent">是否监听外部修改</param>
        public XmlConfig(string xmlFile, bool enabledChangedEvent)
        {
            if (string.IsNullOrEmpty(xmlFile))
            {
                throw new ArgumentNullException("xmlFile");
            }
            string filePath = PathUtils.GetFileFullPath(xmlFile);

            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException(xmlFile + " not found!", xmlFile);
            }

            this.FileName = xmlFile;
            this.m_rwLock = new ReadWriteLock();
            using (var fs = this.GetFileStream(false))
            {
                this.Refresh(fs);
            }

            this.EnabledChangedEvent = enabledChangedEvent;
            var info = new FileInfo(filePath);

            this.m_fileWatcher                = new FileSystemWatcher();
            m_fileWatcher.Path                = info.Directory.FullName;
            m_fileWatcher.Filter              = info.Name;
            m_fileWatcher.Changed            += fileWatcher_Changed;
            m_fileWatcher.NotifyFilter        = NotifyFilters.CreationTime | NotifyFilters.LastWrite;
            m_fileWatcher.EnableRaisingEvents = this.EnabledChangedEvent;
        }
Example #22
0
 public void CannotWriteWhileWriting()
 {
     using (var x = new ReadWriteLock())
     {
         var ok         = true;
         var doneThread = false;
         using (x.EnterWrite())
         {
             Assert.IsTrue(x.IsCurrentThreadWriter);
             var a = new Thread
                     (
                 () =>
             {
                 IDisposable engagement = null;
                 try
                 {
                     ok &= !x.TryEnterWrite(out engagement);
                 }
                 finally
                 {
                     if (engagement != null)
                     {
                         engagement.Dispose();
                     }
                     doneThread = true;
                 }
             }
                     );
             a.Start();
             a.Join();
         }
         Assert.IsTrue(ok);
         Assert.IsTrue(doneThread);
     }
 }
        internal static void SaveResultsAndClearLucenePool(string luceneIndex)
        {
            ReadWriteLock.TryEnterWriteLock(IndexConstants.ReadWriteLockTimeOutMilliseconds);

            try
            {
                if (IndexReaderPool.TryRemove(luceneIndex, out var indexReader))
                {
                    indexReader.Dispose();
                }

                if (IndexWritesPool.TryRemove(luceneIndex, out var indexWriter))
                {
                    indexWriter.Dispose();
                }

                IndexSearcherPool.TryRemove(luceneIndex, out _);

                IndexGotChanged.AddOrUpdate(luceneIndex, u => 0, (u, v) => 0);
            }
            finally
            {
                ReadWriteLock.ExitWriteLock();
            }
        }
Example #24
0
        public SharedData()
        {
            ReadWriteLock rwLock = new ReadWriteLock();

            readLock        = rwLock.ReadLock;
            writeLock       = rwLock.WriteLock;
            CleanUpInterval = TimeSpan.FromSeconds(60);
        }
 private EntryInfo()
 {
     CourseToEntries =
         new DefaultDictionary <CourseModel, ISet <ISQEntryModel> >(() => new HashSet <ISQEntryModel>());
     ProfessorToEntries =
         new DefaultDictionary <ProfessorModel, ISet <ISQEntryModel> >(() => new HashSet <ISQEntryModel>());
     Entries = new HashSet <ISQEntryModel>();
     Lock    = new ReadWriteLock();
 }
 /// <summary>
 /// Removes each node of the collection
 /// </summary>
 public new void Clear()
 {
     ReadWriteLock.AcquireWriterLock(-1);
     while (this.Count > 0)
     {
         this[0].Remove();
     }
     ReadWriteLock.ReleaseWriterLock();
 }
Example #27
0
        public void CanEnterWrite()
        {
            var x = new ReadWriteLock();

            using (x.EnterWrite())
            {
                Assert.IsTrue(x.IsCurrentThreadWriter);
            }
        }
Example #28
0
 public void ReentryReadToWriteRaceCondition()
 {
     using (var w = new ManualResetEvent(false))
     {
         using (var x = new ReadWriteLock(true))
         {
             var         enterCount   = 0;
             var         doneCount    = 0;
             var         errorCount   = 0;
             var         successCount = 0;
             ThreadStart tmp          = () =>
             {
                 using (x.EnterRead())
                 {
                     Interlocked.Increment(ref enterCount);
                     w.WaitOne();
                     // If a thread is a reader it can become a writer as long as there are no other readers
                     // When we have multiple readers trying to become a writer...
                     try
                     {
                         // write mode is requested and reserved by one thread - others fail
                         using (x.EnterWrite())
                         {
                             Interlocked.Increment(ref successCount);
                         }
                     }
                     catch (InvalidOperationException)
                     {
                         Interlocked.Increment(ref errorCount);
                     }
                 }
                 Interlocked.Increment(ref doneCount);
             };
             var threads = new Thread[5];
             for (var index = 0; index < 5; index++)
             {
                 threads[index] = new Thread(tmp);
             }
             for (var index = 0; index < 5; index++)
             {
                 threads[index].Start();
             }
             do
             {
                 Thread.Sleep(10);
             } while (enterCount < 5);
             w.Set();
             for (var index = 0; index < 5; index++)
             {
                 threads[index].Join();
             }
             Assert.AreEqual(5, doneCount);
             Assert.AreEqual(1, successCount); // One succeds - the thread that succeds to reserve write waits for others to leave
             Assert.AreEqual(4, errorCount);   // The others get InvalidOperationException - the threads that fail the reserve fail
         } // This code results in a dead lock in a not reentrant ReadWriteLock
     }
 }
Example #29
0
        private TermInfo()
        {
            IdToTerm     = new OptionalDictionary <int, TermModel>();
            StringToTerm = new OptionalDictionary <string, TermModel>();
            Ids          = new SortedSet <int>();
            IdHashSet    = new HashSet <int>();

            Lock = new ReadWriteLock();
        }
Example #30
0
 public void WriteWaitsMultipleReadsToFinish() // TODO: Review
 {
     using (var w0 = new ManualResetEvent(false))
     {
         using (var w1 = new ManualResetEvent(false))
         {
             using (var x = new ReadWriteLock())
             {
                 var   ok      = false;
                 int[] z       = { 0 };
                 var   threads = new Thread[5];
                 for (var index = 0; index < 5; index++)
                 {
                     threads[index] = new Thread
                                      (
                         () =>
                     {
                         w0.WaitOne();
                         using (x.EnterRead())
                         {
                             w1.Set();
                             Interlocked.Increment(ref z[0]);
                             Thread.Sleep(10);
                         }
                     }
                                      );
                 }
                 var a = new Thread
                         (
                     () =>
                 {
                     w1.WaitOne();
                     using (x.EnterWrite())
                     {
                         Assert.IsTrue(x.IsCurrentThreadWriter);
                         ok = Interlocked.Increment(ref z[0]) == 6;
                     }
                 }
                         );
                 for (var index = 0; index < 5; index++)
                 {
                     threads[index].Start();
                 }
                 a.Start();
                 w0.Set();
                 for (var index = 0; index < 5; index++)
                 {
                     threads[index].Join();
                 }
                 a.Join();
                 Assert.IsTrue(ok);
                 Assert.AreEqual(7, Interlocked.Increment(ref z[0]));
             }
         }
     }
 }
Example #31
0
            public Locks(int concurrencyLevel)
            {
                m_locks           = new ReadWriteLock[concurrencyLevel];
                m_lockWriteCounts = new int[concurrencyLevel];

                for (int i = 0; i < m_locks.Length; i++)
                {
                    m_locks[i] = ReadWriteLock.Create();
                }
            }
        public void TestReadWriteLock_NonConcurrent()
        {
            using (var rwlock = new ReadWriteLock())
            {
                using (rwlock.EnterReadScope()) { }
                using (rwlock.EnterWriteScope()) { }
                using (rwlock.EnterUpgradeableReadScope())
                using (rwlock.EnterWriteScope()) { }

                rwlock.Dispose();
            }
        }
        public void TestReadWriteLock_NoWriteWhileReading()
        {
            // ReSharper disable AccessToModifiedClosure
            // ReSharper disable AccessToDisposedClosure
            // ReSharper disable ImplicitlyCapturedClosure
            using (var rwlock = new ReadWriteLock())
            {
                string value = "foo";

                const string expected = "foo";
                string actual = null;

                var ewh1 = new EventWaitHandle(false, EventResetMode.ManualReset);
                var ewh2 = new EventWaitHandle(false, EventResetMode.ManualReset);

                var task1 = Task.Factory.StartNew(() =>
                {
                    using (rwlock.EnterReadScope())
                    {
                        ewh1.Set();
                        Assert.False(ewh2.WaitOne(TimeSpan.FromMilliseconds(100)));
                        Thread.Sleep(100);

                        actual = value;
                    }
                    Assert.True(ewh2.WaitOne(TimeSpan.FromSeconds(5)));
                });

                var task2 = Task.Factory.StartNew(() =>
                {
                    Assert.True(ewh1.WaitOne(TimeSpan.FromSeconds(5)));
                    using (rwlock.EnterWriteScope())
                        value = "bar";
                    ewh2.Set();
                });

                Assert.True(task1.Wait(TimeSpan.FromSeconds(5)));
                Assert.True(task2.Wait(TimeSpan.FromSeconds(5)));

                Assert.AreEqual(expected, actual);
            }
            // ReSharper restore ImplicitlyCapturedClosure
            // ReSharper restore AccessToDisposedClosure
            // ReSharper restore AccessToModifiedClosure
        }
Example #34
0
 static public int Main(String[] args)
   {
   const int READER_COUNT = 4;
   const int WRITER_COUNT = 4;
   Thread[]	thrdReaders = new Thread[READER_COUNT];
   Thread[]	thrdWriters = new Thread[WRITER_COUNT];
   ReadWriteLock			XYZ		= new ReadWriteLock( );
   XYZ.OutX = 0;
   XYZ.ReadX = 0;
   XYZ.WriteX = 10;
   ThreadStart				reader	= new ThreadStart(XYZ.ReaderFunc);
   ThreadStart				writer	= new ThreadStart(XYZ.WriterFunc);
   for (int i=0;i<READER_COUNT;i++)
     {
     thrdReaders[i] = new Thread(reader);
     thrdReaders[i].Start( );
     }
   for (int i=0;i<WRITER_COUNT;i++)
     {
     thrdWriters[i] = new Thread(writer);
     thrdWriters[i].Start( );
     }
   for (int i=0;i<READER_COUNT;i++)
     {
     thrdReaders[i].Join();
     }
   for (int i=0;i<WRITER_COUNT;i++)
     {
     thrdWriters[i].Join();
     }
   return failed;
   }
Example #35
0
 public UserTokenCache()
 {
     _tokens = new Dictionary<string, IUserToken>();
     _mutex = new ReadWriteLock();
 }