Reputation: 12533
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 ?
Upvotes: 6
Views: 1209
Reputation: 1341
you can check for the disposed state of the object using an boolean variable which will help the dispose method from going into an infinite loop
class SomeClass : IDisposable
{
bool _disposed = false;
public void Dispose()
{
while (true && !_disposed)
{
_disposed = true;
Console.WriteLine("disposed");
}
}
~SomeClass()
{
Dispose();
}
}
Upvotes: 0
Reputation: 941635
It's rather immaterial what happens. The CLR will terminate the program, there is a 2 second timeout on a finalizer.
Upvotes: 8