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:

  1. a thread hitting enterwritelock while that thread has write lock, , lock not created lockrecursionpolicy.supportsrecursion. don't create lockrecursionpolicy.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).

  2. a thread hitting enterwritelock when 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

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -