在析构函数访问ConcurrentDictionary [英] Accessing ConcurrentDictionary in destructor

查看:166
本文介绍了在析构函数访问ConcurrentDictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包装< T>其中T:类包装了我的对象。我保存的WeakReference<包装< T>> ConcurrentDictionary ,以实现对弱引用的线程安全的高速缓存这被自动清理时需要别的东西的内存不可变对象。我需要调用 ConcurrentDictionary.TryRemove 包装析构函数释放在字典中的弱引用不再指向一个有效的对象。

I have a Wrapper<T> where T : class that wraps around my objects. I store WeakReference<Wrapper<T>> in a ConcurrentDictionary, to implement weakly-referenced thread-safe cache for immutable objects that gets automatically cleaned up when memory is required for something else. I need to call ConcurrentDictionary.TryRemove in the Wrapper destructor to free the weak references in the dictionary that no longer point to a valid object.

这是众所周知的,我们不应该使用,因为里面的死锁的风险析构函数任何锁定。所以我想,我可以使用 ConcurrentDictionary.TryRemove 安全的析构函数?恐怕也可能已被使用实施自旋锁或其它一些工具,因而仍有presents在析构函数中使用时死锁的危险。

It is well-known that we should not use any locking inside destructors because of the risk of dead-lock. So I wonder, can I use ConcurrentDictionary.TryRemove safely in a destructor? I am afraid it might have been implemented using SpinLock or some other tool and thus still presents a risk of dead-lock when used in destructor.

推荐答案

您可以看到ConcurrentDictionary的实施,在此<一个href="http://referencesource.microsoft.com/#mscorlib/system/Collections/Concurrent/ConcurrentDictionary.cs,2e5ef5704344a309"相对=nofollow>地点和TryRemove实现使用锁(...)。

You can see the implementation of the ConcurrentDictionary at this location and the TryRemove implementation uses 'lock(...)'.

你可以做的析构函数里面使用线程池来从字典执行删除操作的项目。你仍然需要标记的包装实例作为不再有效,因此,如果调用了它的任何终结的运行和线程池之间的公共方法去除它,你可以发现这一点,并拒绝来电。

What you could do inside the destructor is use the thread pool to perform the removal of the item from the dictionary. You would still need to mark the wrapper instance as no longer valid, so that if a call is made to any of its public methods between the finalizer running and the thread pool removing it, you could detect this and reject the call.

这篇关于在析构函数访问ConcurrentDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆