What is meant by “managed” vs “unmanaged” resources in .NET?

前端 未结 5 615
余生分开走
余生分开走 2020-11-28 03:29

What is meant by the terms managed resource and unmanaged resource in .NET? How do they come into the picture?

5条回答
  •  情话喂你
    2020-11-28 03:36

    The term "unmanaged resource" is usually used to describe something not directly under the control of the garbage collector. For example, if you open a connection to a database server this will use resources on the server (for maintaining the connection) and possibly other non-.net resources on the client machine, if the provider isn't written entirely in managed code.

    This is why, for something like a database connection, it's recommended you write your code thusly:

    using (var connection = new SqlConnection("connection_string_here"))
    {
        // Code to use connection here
    }
    

    As this ensures that .Dispose() is called on the connection object, ensuring that any unmanaged resources are cleaned up.

提交回复
热议问题