What objects does the garbage collector not clean?

The static analysis tool keeps telling me that my C # code contains resource leaks.

Here is an example:

StringReader reader = new StringReader(...); 

// do something with reader

...

} // static analysis tool cries that I've leaked **reader**

Is my tool right? If so, why?

Edit (response to comment). - My static analysis tool says that I have a bunch of resource leaks. I know from this forum that some Java AWT objects must be explicitly freed, otherwise a leak will occur. Are there C # objects that need to be explicitly freed?

+5
source share
9 answers

Yes, your code is leaking a lot. It should be like this:

using (StringReader reader = new StringReader(...))
{

}

, IDisposable, , , Dispose .


UPDATE:

: .NET IDisposable, Dispose. , (, , , ..), /, Dispose. .NET - , , try/finally:

var myRes = new MyResource(); // where MyResource implements IDisposable
try
{
    myRes.DoSomething(); // this might throw an exception
}
finally
{
    if (myRes != null)
    {
        ((IDisposable)myRes).Dispose();
    }
}

, #, , , , PITA. using:

using (var myRes = new MyResource())
{
    myRes.DoSomething(); // this might throw an exception
}

.

+13

, StringReader , MemoryStream . ( MemoryStream , ... .)

, , IDisposable . (, ) , .

, , :

StreamReader reader = new StreamReader("file.txt");
...

reader ( finally using statement), , - , . - ​​ , , .

+6

, StringReader. .Dispose(). , using :

using (StringReader reader = new StringReader(...))
{
    // your code
}

Dispose() , ( finally).

+2

, , StringReader , .

, , . , , , .

, IDisposable. , , . , object.Dispose(); (var x =...) {}.

MS, IDisposable , (, ). MSDN, , , IDisposable, dispose(),

. ( , ), , IDisposable using. . , , , , ( ), , .

- ( ), . , (tm)

+2

. , , , , (, , , , ). "" -, "" , . , , , , Dispose , .

, Dispose, , , . , , , , , . Dispose, , .

+2

, Close , , MSDN:

Close Dispose, .

, , ( ).

: , GC Dispose IDisposable objects. Close ( Dispose).

+1

, " " GC .

0

. , . , , .

using, .

using (sr) {
 // your code
}
0

The garbage collector will collect everything that no longer has a link to it. Your example readerwill ultimately be compiled (although no one can tell when).

However, the "static analysis tool" complains that you are not calling manually Dispose().

StringReader reader = ...
...
reader.Dispose();

In this particular case, this is probably not a big deal. However, when dealing with many input / output classes (* Stream, * Reader, etc.), it’s good when you are done. You can use usingto help:

using(StringReader reader = ...) {
    ...
}  //reader is automatically disposed here
0
source

All Articles