public async Task <bool> Add(T obj) { if (!pool.ContainsKey(obj.HashStr)) { try { await poolLocker.EnterWriteLock(); if (!pool.ContainsKey(obj.HashStr)) { pool.Add(obj.HashStr, obj.Clone <T>()); return(true); } } finally { poolLocker.ExitWriteLock(); } } return(false); }
public void TestPool() { var locker = new ReadWriteLockAsync(); Task.Run(async() => { await locker.EnterReadLock(); await Task.Delay(1000); locker.ExitReadLock(); }); Task.Run(async() => { await locker.EnterReadLock(); await Task.Delay(1000); locker.ExitReadLock(); }); Task.Run(async() => { await locker.EnterReadLock(); await Task.Delay(1000); locker.ExitReadLock(); }); Task.Run(async() => { await locker.EnterWriteLock(); await Task.Delay(1000); locker.ExitWriteLock(); }); Task.Run(async() => { await locker.EnterReadLock(); await Task.Delay(1000); locker.ExitReadLock(); }); }