Are resources freed when the object is garbage dumped?

I asked this question, and although I believe that I know the answer, I believe that I should be 100% sure that I will begin to spread misinformation!

I have this object:

public class MyObj(){
    private SqlConnection conn;

    public MyObj(string connString){
        var stream = File.Open(@"c:\\file.txt");
        conn = new SqlConnection(connString);
    }
}

When this object is created, a file descriptor is associated with the file and a connection to the database is created. None of them have Dispose, as it should.

When this object goes out of scope and eventually collects garbage, are these two resources then freed or left in memory?

+3
source share
3 answers

When this object goes out of scope and eventually collects garbage, are these two resources then freed or left in memory?

- API - , , SafeHandle, . , , , , , API-, Microsoft, .

, :)

+2

, , , finalizer, . , , . , :

, ?

, , .

, , , . , , , - , -.

.NET IDisposable, . FileStream, .

IDisposable , Dispose, . GC.SuppressFinalize(this), IDisposable . - , , . , , , .

, , . , SafeHandle. , IDisposable Dispose IDisposable.

+1

Short answer: they are automatically released.

Only once, several years ago, I received an inexplicable memory leak due to the fact that the object was not released. At that time, I need to make an explicit call to the garbage collector to fix the problem.

I never found a real reason, maybe an error in the infrastructure, maybe something is related to the OS resource, but I can say that 99.99% of the time, you can be free from worrying about it in C #.

0
source

All Articles