will this lead to memory leak? it shouldn't, should it?
in my code i have something like
Code:
FileStream fs = new Filestream("file.txt", FileMode.Open);
processFile(fs);
|
|
|
processFile(Filestream strm) {
...do something
strm.close();
}
If I am closing the stream in the function processFile(), would that actually cause any memory leak? I mean strm and fs all point to the same objects..
so techincally if i call strm.close(), the filestream itself would be closed, and strm will be destroyed on function call return since it is a local variable. And since fs refers to a closed stream, it should be picked up by the garbage collector right?
please let me know.
thnx
Re: will this lead to memory leak? it shouldn't, should it?
Quote:
and strm will be destroyed on function call return since it is a local variable.
The variable/reference is 'destroyed'. But the object will exist until the fs reference runs out of scope. Then the garbage collector (when it kicks in) will pick up the object and dispose it.
- petter
Re: will this lead to memory leak? it shouldn't, should it?
I believe it should get picked up by the garbage collection.
Personally, IMHO, I believe responsibility for closing the FileStream lies within the scope of the object that created it. If used on a class basis, that class is responsible for opening and closing it. If used in a function scope, that function should both open and close it.
.. and just to be sure, use 'using' instead
Code:
using (FileStream fs = new Filestream("file.txt", FileMode.Open))
{
processFile(fs);
}
Regards
Alan
Re: will this lead to memory leak? it shouldn't, should it?
But as far as I know, it will be closed, so the file's handle will be released, and the fs cannot be used any more, despite it still exists as .NET object.