0

What purpose does “using” serve when used the following way:-

ONE EXAMPLE IS THIS, (AN ANSWERER- @richj - USED THIS CODE TO SOLVE A PROBLEM THANKS)

private Method(SqlConnection connection)
{
    using (SqlTransaction transaction = connection.BeginTransaction())
    {
        try
        {
            // Use the connection here
            ....

            transaction.Commit();
        } 
        catch
        {
            transaction.Rollback();
            throw;
        }
    }
}

OTHER EXAMPLE I FOUND WHILE READING ON MICROSOFT SUPPORT SITE

public static void ShowSqlException(string connectionString)
{
    string queryString = "EXECUTE NonExistantStoredProcedure";
    StringBuilder errorMessages = new StringBuilder();

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        try
        {
            command.Connection.Open();
            command.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            for (int i = 0; i < ex.Errors.Count; i++)
            {
                errorMessages.Append("Index #" + i + "\n" +
                    "Message: " + ex.Errors[i].Message + "\n" +
                    "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
                    "Source: " + ex.Errors[i].Source + "\n" +
                    "Procedure: " + ex.Errors[i].Procedure + "\n");
            }
            Console.WriteLine(errorMessages.ToString());
        }
    }
}

I AM doing at top of page as using system.data.sqlclient etc so why this using thing in middle of code,

What if I omit it (I know the code will work) but what functionality will I be losing

4

5 回答 5

6

When you leave the using() block your connection will be closed or similar cleanup duties are performed. This is achieved by calling the object's Dispose() method.

于 2010-06-17T06:06:57.453 回答
5

直接来自MSDN:

using (Font font1 = new Font("Arial", 10.0f)) 
{
  byte charset = font1.GdiCharSet;
}

相当于:

{
  Font font1 = new Font("Arial", 10.0f);
  try
  {
    byte charset = font1.GdiCharSet;
  }
  finally
  {
    if (font1 != null)
      ((IDisposable)font1).Dispose();
  }
}

这是一种更简短、更简洁的说法:我想用我创造的这个东西来做各种美妙的事情,我希望框架在我完成后清理我的操场。

它通常与分配资源的类(流、数据库连接......)一起使用,因为您可能会在使用完这些资源后忘记或忽略释放这些资源。与using你不配合资源管理,你很可能不会泄漏资源。

PS 另一个using(如中using System.Web)是using 指令,我说的是using 语句

于 2010-06-17T06:09:52.940 回答
5

我认为您指的是using关键字的两种不同用法。

当(通常)在文件顶部时,它声明要导入命名空间。请参阅“使用指令”

using System.Collections;

namespace XYZ
{
}

在函数内部声明时,它为变量声明有限的生命周期和可能的范围(如果同时声明),以便IDisposable在块关闭后自动调用它的接口。请参阅“使用语句”

public void MyMethod()
{
    using (var conn = new SqlConnection(...))
    {
         // Do stuff
    }
}

是否等效于:

public void MyMethod()
{
    SqlConnection conn;
    try
    {
        conn = new SqlConnection(...);
        // Do stuff
    }
    finally
    {
        conn.Dispose();
    }
}
于 2010-06-17T06:12:59.877 回答
2

在幕后,它将您的代码包装在 try/finally 块中,并在 finally 块中调用 IDiposable.Dispose() 确保清理所有资源。

基本上它可以为您省去以下操作的麻烦:

SqlTransaction transaction = connection.BeginTransaction();

try
{ 
  //some code;
}
finally
{
  transaction.Dispose();
}
于 2010-06-17T06:09:41.147 回答
1

正如小偷大师所说-当退出使用块时,SQLTransaction 或 SQLConnection 将关闭。无论它是通过返回还是抛出异常退出。

如果您省略使用,您必须自己关闭事务/连接。通过使用系统会自动为您执行此操作。

于 2010-06-17T06:10:07.607 回答