Finalizer stuck in an infinite loop

I came across an interview question that I didn’t know the answer (a little help :)) well he stated something like:

Class SomeClass : IDisposable { public void Dispose() { while(true) { } } ~SomeClass() { Dispose(); } } 

1) Did the object end when it no longer refers after the next GC? My answer was NO, because the stream of finalization was stuck in an endless loop.

2) What can be done in Dispose to complete the finalization, and how many times the cycle will continue until the object is Disposed (excluding the time that will be spent in the next Gen).

I don’t really understand the exact question (2). I did not have time...

Not knowing the answer, I put a static counter that reaches 3, and causes a break and stated that 3 which will technically work :), but this is not an answer

I assume this has something to do with GC.SupressFinalize ()? perhaps calling GC.SupressFinalize () before entering the loop?

Any ideas, if not answers to an unclear question, more than what they could strive for?

+6
source share
2 answers

It doesn’t matter what happens. The CLR terminates the program; there is a 2 second timeout on the finalizer.

+8
source

you can check the state of an object using a boolean that helps the delete method go into an infinite loop

 class SomeClass : IDisposable { bool _disposed = false; public void Dispose() { while (true && !_disposed) { _disposed = true; Console.WriteLine("disposed"); } } ~SomeClass() { Dispose(); } } 
0
source

Source: https://habr.com/ru/post/905755/


All Articles