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: Rhys Weatherley
Subject: Re: [DotGNU]question about Finalize in C#
Date: Thu, 05 Sep 2002 09:05:36 +1000

Ian Fung wrote:
> 
> i asked this in the chan but no one was around. this isnt about developing
> pnet or anything, but i ifigured someone would know the answer to this here
> =).
> 
> 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?

Finalize can act as a final back-stop, in case the user did
not call close.  In C#, the best way to do cleanup is as follows:

1. Implement the IDisposable interface and its "Dispose" method.
2. "Dispose" closes handles, sockets, etc, if they aren't null,
   and then sets them to null.
3. "Close" and "Finalize" call "Dispose" internally.

It is possible that "Dispose" may be called multiple times
(e.g. once in "Close" and again from "Finalize"), so it must
be hardened against such usage.

Implementing the IDisposable interface allows you to use the
"using" construct.  e.g.

    using (FileStream file = new FileStream("xyz"))
    {
        ...
    }

The "using" statement automatically calls "Dispose" when the
statement body ends or throws an exception.

> also.
> 
> I know what a short weak reference is. what is a long weak reference?

Got me.  I always thought there were just "weak" and "strong". :-)
If you saw it in an MS doc, then it may have something to do with
incremental garbage collection, which we aren't currently using.
Any GC experts care to comment?

Cheers,

Rhys.


reply via email to

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