Question

  1. Are the queries executed in a C# progamm using System.Data.SqlClient namespace cosnidered managed or umanaged code?

  2. Every time the connection is closed , (conn.Close() method is used) does the resource consider released or we have to dispose it in order to get released?

Was it helpful?

Solution

System.Data.SqlClient itself is managed code. However, it is built on top of several other libraries. Some of them are managed code and some are not.

  1. The query itself is executed by a database. So, the text of the query (the part that is hard-coded in your program) would be considered managed code, but once the command is sent to a database, it is no-longer managed.

  2. Once the .close command is executed, the connection itself is released from your .net app and returned to the connection pool (part of OLEDB, ODBC and/or other sub-systems). At that point, the connection is freed and the unmanaged part is released. Dispose will do everything close does and release other managed parts (connection string, etc).

It is always a good idea to call dispose on any object that implements it (or wrap it in a using block, like @IRSOG showed). In this case, it isn't particularly dangerous to just call close(). I wouldn't make a habit of it.

OTHER TIPS

About second question:

The Close method rolls back any pending transactions. It then releases the connection to the connection pool, or closes the connection if connection pooling is disabled.

Edited

The following example creates a SqlConnection, opens it, displays some of its properties. The connection is automatically closed at the end of the using block.

private static void OpenSqlConnection(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
        Console.WriteLine("State: {0}", connection.State);
    }
}

Edited

You need a using for every object you create that implements IDisposable. That includes the SqlCommand and the SqlConnection.If you use using statement, they will dispose after using block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top