I need a lock similar to the one from this answer from Stephen Cleary: https://stackoverflow.com/a/31194647/4381408
However, I also need to be able to lock on all keys at the same time. I'm using Stephen Cleary's AsyncEx library as well, so I thought of combining the AsyncDuplicateLock with an AsyncReaderWriterLock like this:
public sealed class AsyncDuplicateReaderWriterLock
{
private AsyncReaderWriterLock _rwLock = new AsyncReaderWriterLock();
private AsyncDuplicateLock _duplicateLock = new AsyncDuplicateLock();
public IDisposable ReaderLock(object key)
{
return CollectionDisposable.Create(
_rwLock.ReaderLock(),
_duplicateLock.Lock(key)
);
}
public async Task<IDisposable> ReaderLockAsync(object key)
{
return CollectionDisposable.Create(
await _rwLock.ReaderLockAsync(),
await _duplicateLock.LockAsync(key));
}
public IDisposable WriterLock()
{
return _rwLock.WriterLock();
}
public async Task<IDisposable> WriterLockAsync()
{
return await _rwLock.WriterLockAsync();
}
}
This way, I can use ReaderLock to lock on a key, and WriterLock to lock on all keys. It's critical I get this right so I want to be sure that there's no way for this to deadlock or not lock properly. I don't feel confident enough about it.
So would this work, be somewhat efficient, and be threadsafe?
Thanks for the help!