dotgnu-general
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [DotGNU]question about Finalize in C#


From: Juhani Honkala
Subject: Re: [DotGNU]question about Finalize in C#
Date: Wed, 4 Sep 2002 23:23:23 +0300 (EEST)

On Wed, 4 Sep 2002, Ian Fung wrote:

> C# Q: I understand what Finalize does. but from what i understand, it
>          is not guarentteed to be called (ie only when the GC is called) and
>          it also takes two calls to teh GC to retrieve the object. what kind
>         of cleanup would you want to put in Finalize? i mean for example, if
>           i open a file, wouldnt i want to close it outside of Finalize to
>           make sure it closes everytime instead of putting it in Finalize?
> 

C# (unfortunately) lacks of explicit destruction scheme as in C++.

You should never depend on a finalizers to release any criticial 
resources. Instead of writing finalizer write an explicit release
method like Dispose() and use Finalize() only as a safety net or last
resort (in case user forgets to call Dispose()). Remember to call
superclass Finalize() if you override Finalize(). (If my memory serves
me right there's an interface in C# called IDispose that's tries to
somehow standardize use of explicit destruction, i'm not 100% sure tho) 

i'm not sure how c# syntax do but in Java it would something like

public void dispose() {
 //release all critical resources here
}

protected void finalize() {
   try {  
      dispose(); 
   } finally {
      super.finalize()
   }
}


Generally you should avoid using only finalizers to free resources,
in some situations it might be acceptable like in freeing non-critical
native resources or something but these cases should be considered as 
exception. 



if things are different in C# than in Java, feel free to correct
me ;)

juhani



reply via email to

[Prev in Thread] Current Thread [Next in Thread]