What's the point of the garbage collector

SqlConnection connection = new SqlConnection(FROM_CONFIGURATION) 
SqlCommand command = new SqlCommand("SomeSQL", connection); 
connection.Open(); 
command.ExecuteNonQuery(); 
command.Dispose(); 
connection.Dispose();

It is recommended that the above code include try / catch (or use), so that when an exception occurs, all resources are located correctly.

But if you need to worry about recycling manually, then what a GC point! Isn't GC there taking care of this for the encoder?

+3
source share
15 answers

, GC , , . , , ( , ), . Dispose , , . , , GC . .

, 'using' .

+15

, .

, GC . , (, ) , , .

, - , , .

, GC . , , , , , .

, GC , , . .

.

+7

, GC?! GC ?

, , GC. , .

+6

, :

class MonkeyGrabber : IDisposable {
   public MonkeyGrabber() { /* construction grabs a real, live monkey from the cage */
   public void Dispose() { Dispose(true); /* releases the monkey back into the cage */ }
   // the rest of the monkey grabbing is left as an exercise to grad student drones
}

class MonkeyMonitor {
    public void CheckMonkeys() {
        if (_monkeyPool.GettingTooRowdy()) {
            MonkeyGrabber grabber = new MonkeyGrabber();
            grabber.Spank();
        }
    }
}

MonkeyMonitor , , - , , , . , , . , MonkeyGrabber, . . , : , IDisposable, , . GC .

, . , , , GC , , , , , GC .

IDisposable.

- RAII.

+5

, IDisposable, , , . , . , , , , , , //.

+4

GC , . , , , , , ( C/++), , , , . , , , . , , using db :

using (SqlConnection connection = new SqlConnection(...))
using (SqlCommand command = connection.CreateCommand())
{
   ...
}

dispose , , .

+3

GC - , . , , -, .., / , GC, .

using:

using (SqlConnection connection = new SqlConnection(FROM_CONFIGURATION))
using (SqlCommand command = new SqlCommand("SomeSQL", connection))
{
  connection.Open(); 
  command.ExecuteNonQuery(); 
  command.Dispose(); 
  connection.Dispose();
}

, , , , using.

+2

... GC ; ... , ... ( )

OP , .net-specific, , GC , , using IDisposable, .

. , ++ () , , RAII .

cPython . , . "" , , , ++ RAII. , , . , Java .NET. .NET , cPython .

, OP , , , (, , GC, using RAII) , .

+2

(, , Dispose(), , ). GC ( , ), .

+1

#, , , , . , , . , , . .

+1

(GC) .NET .NET Common Language Runtime (CLR) .NET. GC ; , , .NET-. , .

, - , .. Close() / Dispose(), , GC.

+1

. . !

+1

GC , . .

0

GC , , . .NET .

0

, . , , " " . / , , .

, , , ( -), , .

0

Source: https://habr.com/ru/post/1698534/


All Articles