Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can CERs be used to guarantee that finalize is never called?

We have a very tricky interop problem wherein the thread used to initialize a 3rd-party system has to be the same thread used to terminate it. Failure to do this results in a deadlock. We are performing interop from a WCF service hosted in IIS. Currently this cleanup is done in disposal and normally works very well. Unfortunately, under heavy load IIS will do a rude unload and we never get to call dispose. We can move the shutdown logic into a critical finalizer but that doesn't help since we no longer have access to the initializing thread! At this point our only recourse seems to be notifying the CLR that the AppDomain is now likely in a corrupted state. However, I'm not sure how to do that (or if it's even possible). It may be that this is the utility of contracts at a class level but I admit I don't really understand those fully.

EDIT: Alternatively, this is could be viewed as a thread affinity problem in the finalizer. If anyone has a clever solution to that, I'm all ears :)

like image 692
Jeff Avatar asked Mar 12 '12 20:03

Jeff


People also ask

Is finalize guaranteed to be called?

finalize method is not guaranteed. This method is called when the object becomes eligible for GC. There are many situations where the objects may not be garbage collected.

What is an alternative for finalized method?

The phantom reference can be used instead of a finalize method, guaranteeing that the object is not resurrected during finalization. This allows the object to be garbage collected in a single cycle, rather than needing to wait for a second GC cycle to ensure that it has not been resurrected.

Why finalize () method should be avoided?

“This method is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock.” So, in one way we can not guarantee the execution and in another way we the system in danger.

Which of the following methods tells the garbage collector not to call finalize?

Dispose implementation to prevent the garbage collector from calling Object. Finalize on an object that does not require it. Typically, this is done to prevent the finalizer from releasing unmanaged resources that have already been freed by the IDisposable. Dispose implementation.


1 Answers

Try to split the code that depends on that native dependency to a standalone Windows service application if possible. If it cannot work well with WCF/IIS, you should avoid the conflicts instead of fighting against it.

like image 150
Lex Li Avatar answered Sep 30 '22 14:09

Lex Li