Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage Colletion with IDisposable

I was talking with a person about using() statement.

He said if we do NOT use using() statement for something like a StreamWriter, if any exception happens, the resource will NEVER get collected.

I do understand to use using() statement, but I don't agree that the resource will never be collected. I think using() statement will call dispose() method at the end, which can make the collection much faster. However, even if we don't use using(), we don't call dispose(), the resource can still be collected by gabage collection, although it may take much longer time.

Who do you agree with?

ps. I know what you all are saying. It's important to use using() statement. I just want to find out if the resource will definitely never get collected if we don't do it?

like image 534
Frank Avatar asked Dec 02 '22 02:12

Frank


2 Answers

Let's be clear on this. Suppose the resource in question is a file handle. The garbage collector knows nothing about the file handle or how to free it. The file handle is just an integer.

If the StreamWriter that is holding on to the file handle gets garbage collected then the garbage collector will put the object onto the finalization queue. When the finalization queue runs, it will call the finalizer of the object, and that is what releases the file handle.

Is that all clear? The garbage collector does not free the resource; the only resource the garbage collector knows about is objects in memory. Before the object is freed it is finalized, so it is the object itself that knows how to free the resource.

like image 134
Eric Lippert Avatar answered Dec 18 '22 08:12

Eric Lippert


using(x) is a deterministic pattern. It ensures that Dispose() is called on the implementor when a particular point in the execution flow is passed. The GC on the other hand is not deterministic, because you don't know exactly when the object will be actually disposed. using ensures that the object will execute its cleanup code (whatever that is) when you expect it to, rather than some time in the future.

like image 30
kprobst Avatar answered Dec 18 '22 08:12

kprobst