Here's the task: I need to block based on the file name. There may be up to a million different file names. (This is used for large-scale disk-based caching). I want to use low memory and low search times, which means that I need a GC'd lock dictionary. (Only built-in locks can be present in a dict).
The callback may take several minutes, so global locking is unacceptable. High throughput is critical.
I posted my current solution below, but I'm not happy with the complexity.
EDIT: Please do not submit solutions that are not 100% correct. For example, a solution that allows you to exclude a lock from the dictionary between the “get object lock” phase and the “lock” phase is NOT correct, regardless of whether it is an “accepted” design pattern or not.
Is there a more elegant solution than this?
Thanks!
[EDIT: I updated my code to use a loop or recursion based on RobV's suggestion]
[EDIT: code updated again to allow timeouts and a simpler call pattern. This will probably be the last code I use. All the same basic algorithm as in the original message.]
[EDIT: updated code again to deal with exceptions inside callback without orphaned lock objects]
public delegate void LockCallback();
Usage example
LockProvider p = new LockProvider(); bool success = p.TryExecute("filename",1000,delegate(){
Nathanael jones
source share