1

我维护了一个用于资源访问的 ReaderWriterLockSlim 对象字典:(示例代码在这里很难看,只是让您了解我的目的)

static ConcurrentDictionary<string, ReaderWriterLockSlim> rwResourceLocks =
                                new ConcurrentDictionary<string, ReaderWriterLockSlim>();

并像这样使用:

if (ResourceStore.Exist("resourceID")) {
    if (rwResourceLocks["resourceID"] == null) {
        /* create a new lock in thread-safe way */
    }
    rwResourceLocks["resourceID"].EnderReadLock();
    var rc = ResourceStore.GetResource("resourceID");
    /* further use of rc... */
    rwResourceLocks["resourceID"].ExitReadLock();    
}

资源可以动态添加或删除,并且它们的生命周期是不可预测的(无法监控资源的删除),随着资源量的增长,rwResourceLocks 的大小也会增加,这将导致内存问题。有没有办法解决这个问题?(显然我不能简单地调用 rwResourceLocks.Clear() 来做到这一点)

我知道这有点复杂:(

4

1 回答 1

2

您可以尝试使用ConditionalWeakTable而不是ConcurrentDictionaryConditionalWeakTable当垃圾收集器收集了它的键时,A会自动从字典中删除一个值。

ConditionalWeakTable<object, ReaderWriterLockSlim> _locks;

if (ResourceStore.Exists("resourceID")) {
    var rc = ResourceStore.GetResource("resourceID");
    var lck = _locks.GetValue(rc, () => new ReaderWriterLockSlim());

    lck.EnterReadLock();

    // Use the resource here

    lck.ExitReadLock();
}
于 2016-03-31T10:20:51.160 回答