Suppose I need to clean up some managed resources in a finalizer, or at least record it somewhere in a thread safe way that a clean up is needed. From what I understand, taking locks in a finalizer is strictly verboten but how about the Interlocked class? Is this safe and will it not result in a deadlock?
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.
Also, it seems that all finalizers are run on one thread, is this a guaranteed behavior or just an implementation detail? And if it is just a detail, is this ok to acquire a lock inside finalizers (say, to push jobs in a lock-free queue) provided that the lock will never be taken anywhere else?