sergtk
sergtk

Reputation: 10974

Access non-finalizable objects from finalizer

I want to access object without finalizer from finalizer of other instance.

I know that it is bad idea to access other finalizable object from finalizer because sequence of finalizer call is non-deterministic.

But what about accessing instances without finalizer from finalizer of other objects? I can not figure this out, the only found in the article http://edn.embarcadero.com/article/29365 :

This means that finalizers should never access other finalizable objects (objects without finalizers, however, are just fine)

Is any confirmation of this in MSDN?

Currently I want to acquire lock object with variable of type object but I want to be sure that it is OK and object instance is not freed from memory before accessing it.

Upvotes: 2

Views: 173

Answers (2)

Hans Passant
Hans Passant

Reputation: 941545

Currently I want to acquire lock object with variable of type object

Accessing that object in your finalizer is fine, nothing happened to it. Actually using it a lock statement, that's not so fine. Blocking the finalizer thread tends to byte badly. It has a time-out at program exit, it must complete and get everything finalized within two seconds. You cannot afford a Monitor.TryEnter() to avoid tripping that timeout, that will be a bad resource leak.

And beware the code smell, you should not be releasing whatever native resource you wrote the finalizer for when other threads can still access it. It is gospel that the finalizer can only run when nobody keeps a reference to the object anymore. Which should also mean that there shouldn't be any point in locking anymore since no thread could have a reference anymore. There is no need to protect shared state with a lock when nobody can read or write it.

Keep in mind that actually writing a finalizer tends to be almost always wrong, native resources should be finalized by their corresponding .NET wrapper class. There are many, the low-level ones are the SafeHandle derived classes.

Upvotes: 1

YK1
YK1

Reputation: 7612

Objects are not collected till the time they have a root. Assuming the object instance you are talking about is member of the object that is getting finalized, then that object has been alive all the time - because root is f-reachable queue.

However, I will strongly advise against any locking or blocking in finalizer. It could cause ugly deadlocks.

Upvotes: 0

Related Questions