Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finalizer stuck in infinite loop

Tags:

c#

finalizer

I came across a interview question which i did not know the answer ( little help :) ) well it stated something of the sort :

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

    ~SomeClass()
    {
        Dispose();
    }
}  

1) Does the object get finalized when no longer referenced after the next GC? My answer was NO, because the finalization thread will be stuck on the infinite loop.

2) What could be done in the Dispose to end the finalization and how many times will the loop continue before the object is Disposed ( with out taking in to account the time it will spend in the next Gen )

I am not particularly clear of the exact question (2) .I kinda ran out of time ...

Not knowing the answer I put a static counter that gets to 3 and calls break and stated 3 which technically would work :), but that's not the answer

I'm guessing it as something to do with GC.SupressFinalize() ? maybe calling GC.SupressFinalize() before entering the loop ?

any ideas if not on the answer to the unclear question , more as to what they might of been aiming for ?

like image 383
eran otzap Avatar asked Jan 11 '12 20:01

eran otzap


1 Answers

It's rather immaterial what happens. The CLR will terminate the program, there is a 2 second timeout on a finalizer.

like image 168
Hans Passant Avatar answered Sep 22 '22 02:09

Hans Passant