Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Depending on what you are doing with the files (you say disk based caching so I assume reads as well as writes) then I would suggest trying something based upon <a href="http://msdn.microsoft.com/en-us/library/sb7kah3h.aspx" rel="nofollow">ReaderWriterLock</a>, if you can upgrade to .Net 3.5 then try <a href="http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim%28v=VS.90%29.aspx" rel="nofollow">ReaderWriterLockSlim</a> instead as it performs much better.</p> <p>As a general step to reducing the potential endless recursion case in your example change the first bit of the code to the following:</p> <pre><code>do { // 1) Creation/aquire phase lock (createLock){ // We have to lock on dictionary writes, since otherwise // two locks for the same file could be created and assigned // at the same time. (i.e, between TryGetValue and the assignment) if (!locks.TryGetValue(key, out itemLock)) locks[key] = itemLock = new Object(); //make a new lock! } // Loophole (part 1): // Right here - this is where another thread could remove 'itemLock' // from the dictionary, and potentially, yet another thread could // insert a new value for 'itemLock' into the dictionary... etc, etc.. // 2) Execute phase lock(itemLock){ // May take minutes to acquire this lock. // Real version would specify a timeout and a failure callback. // Trying to detect an occurence of loophole above // Check that itemLock still exists and matches the dictionary lock(createLock){ object newLock = null; validLock = locks.TryGetValue(key, out newLock); validLock = validLock &amp;&amp; newLock == itemLock; } // Only run the callback if the lock is valid if (validLock) callback(); // Extremely long-running callback. } // If we had an invalid lock, we have to try everything over again. } while (!validLock); </code></pre> <p>This replaces your recursion with a loop which avoids any chance of a StackOverflow by endless recursion.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload