What is the main difference of ReaderWriterLockSlim
than regular Lock
?
Since I am trying to achieve async
, await
, I can't use regular Lock
So I am trying to make it work with ReaderWriterLockSlim
However I am getting this error,
System.Threading.LockRecursionException: 'Recursive write lock acquisitions not allowed in this mode.'
Isn't supposed ReaderWriterLockSlim
to make queued threads/tasks to wait until released? So when the currently working thread on the given method is done, isn't the next in queued thread/task supposed to enter the method?
So lets say I have 5 tasks that wanted to access my method written as below and let's name them as A,B,C,D,E
Let's say B got the method and _lockRootAdd
is now locked. Isn't A,C,D,E tasks supposed to wait until lock is released and once released aren't they supposed to enter the method 1 by 1?
private static readonly ReaderWriterLockSlim _lockRootAdd = new ReaderWriterLockSlim();
private static async Task<int> returnRootDomainId(this string srUrl)
{
_lockRootAdd.EnterWriteLock();
try
{
using ExampleCrawlerContext _context = new ExampleCrawlerContext();
string rootDomain = srUrl.NormalizeUrl().returnRootDomainUrl();
var rootDomainHash = rootDomain.SHA256Hash();
var result = await _context.RootDomains.Where(pr => pr.RootDomainUrlHash == rootDomainHash).FirstOrDefaultAsync().ConfigureAwait(false);
if (result == null)
{
RootDomains _RootDomain = new RootDomains();
_RootDomain.RootDomainUrlHash = rootDomainHash;
_context.Add(_RootDomain);
await _context.SaveChangesAsync().ConfigureAwait(false);
await addUrl(rootDomain).ConfigureAwait(false);
}
var result2 = await _context.RootDomains.Where(pr => pr.RootDomainUrlHash == rootDomainHash).FirstOrDefaultAsync().ConfigureAwait(false);
return result2.RootDomainId;
}
finally
{
_lockRootAdd.ExitWriteLock();
}
}