c# - ReaderWriterLockSlim how to wait to enter lock? -
i trying use readerwriterlockslim lock database work in async method this:
readerwriterlock.enterwritelock(); using (var db = new mycontextdb()) { // , alter } readerwriterlock.exitwritelock(); this throws exception multiple threads try enter writelock @ same time. right use lock object thought use readerwriterlockslim try optimisation read/write & upgradeable.
the msdn samples of readerwriterlockslim little confusing me. there simple way have thread wait lock become available? iswritelockheld property says tests if current thread locked. waitingwritecount says gives number of threads waiting enter how make thread wait enter? not find in samples. meant loop until not throw exception? not seem right.
you in comment exception getting lockrecursionexception.
this means somewhere either:
a thread hitting
enterwritelockwhile that thread has write lock, , lock not createdlockrecursionpolicy.supportsrecursion. don't createlockrecursionpolicy.supportsrecursion; recursive locks bad idea; fix fact you're trying obtain lock have. (more on why lock recursion bad discussed @ answer @ https://stackoverflow.com/a/12014173/400547).a thread hitting
enterwritelockwhen has read lock. release read lock first.
there inclusive/exclusive locks (aka "reader/writer locks") allow code obtain write lock when have read lock. though can cause nasty deadlocks explained in answer @ https://stackoverflow.com/a/8807232/400547 luckily readerwriterlockslim not support this. release reader lock first, or use upgradable lock.
or indeed, since work covered involves database, use transaction , have database deal concurrency issues.
Comments
Post a Comment