1
假设我需要清理终结器中的一些托管资源,或者至少以线程安全的方式将其记录在需要清理的地方。根据我的理解,锁定终结者是严格禁止的,但Interlocked类怎么样?这是否安全,是否会导致僵局?可以在终结器中使用互锁吗?
static int deadentries;
~Item() { Interlocked.Increment(ref deadentries); }
public static T Get(int id, Action<T> init) {
T ret;
WeakReference<T> tref;
if (cache.TryGetValue(id, out tref)) {
if (tref.TryGetTarget(out ret)) return ret;
else Interlocked.Decrement(ref deadentries);
}
if (deadentries * 2 > cache.Count) {
// etc. etc.
而且,似乎一切都终结在一个线程中运行,这是有保证的行为,或只是实现的细节?如果只是一个细节,这是否可以在终结器内部获取锁(比如,将任务推入一个无锁队列中),前提是锁永远不会在其他地方使用?