using

using 语句(C# 参考)

Visual Studio 2005
外释放一个或多个对象。
        using (Font font1 = new Font("Arial", 10.0f))
{
}

C# 通过 .NET Framework 公共语言运行库 (CLR) 自动释放用于存储不再需要的对象的内存。内存的释放具有不确定性;一旦 CLR 决定执行垃圾回收,就会释放内存。但是,通常最好尽快释放诸如文件句柄和网络连接这样的有限资源。

using 语句允许程序员指定使用资源的对象应当何时释放资源。为 using 语句提供的对象必须实现 IDisposable 接口。此接口提供了 Dispose 方法,该方法将释放此对象的资源。

可以在到达 using 语句的末尾时,或者在该语句结束之前引发了异常并且控制权离开语句块时,退出 using 语句。

可以在 using 语句中声明对象(如上所示),或者在 using 语句之前声明对象,如下所示:

Font font2 = new Font("Arial", 10.0f);
using (font2)
{
    // use font2
}

可以有多个对象与 using 语句一起使用,但是必须在 using 语句内部声明这些对象,如下所示:

        using (Font font3 = new Font("Arial", 10.0f), 
           font4 = new Font("Arial", 10.0f))
{
    // Use font3 and font4.
}

下面的示例显示用户定义类可以如何实现它自己的 Dispose 行为。注意类型必须从 IDisposable 继承。

using System;

class C : IDisposable
{
    public void UseLimitedResource()
    {
        Console.WriteLine("Using limited resource...");
    }

    void IDisposable.Dispose()
    {
        Console.WriteLine("Disposing limited resource.");
    }
}

class Program
{
    static void Main()
    {
        using (C c = new C())
        {
            c.UseLimitedResource();
        }
        Console.WriteLine("Now outside using statement.");
        Console.ReadLine();
    }
}

有关更多信息,请参见 C# 语言规范中的以下各章节:

  • 5.3.3.17 Using 语句

  • 8.13 using 语句

社区内容 添加
确实如此
  1. //Try catch finally   
  2. try  
  3. catch  (Exception ex) 
  4. finally  
  5. }
using语句的本质

使用using语句实际上生成的IL代码中是一个try, finally代码块,在finally代码块里释放资源。

比如这样一段代码:

            using (SqlConnection conn = new SqlConnection())
{
conn.Open();
throw new Exception("Exception!!");//抛出异常之后能回收SqlConnection对象的资源吗?
}

IL代码可为:

  // Code size       42 (0x2a)
.maxstack 2
.locals init ([0] class [System.Data]System.Data.SqlClient.SqlConnection conn,
[1] bool CS$4$0000)
IL_0000: nop
IL_0001: newobj instance void [System.Data]System.Data.SqlClient.SqlConnection::.ctor()
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: ldloc.0
IL_0009: callvirt instance void [System.Data]System.Data.Common.DbConnection::Open()
IL_000e: nop
IL_000f: ldstr "Exception!!"
IL_0014: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_0019: throw
} // end .try
finally
{
IL_001a: ldloc.0
IL_001b: ldnull
IL_001c: ceq
IL_001e: stloc.1
IL_001f: ldloc.1
IL_0020: brtrue.s IL_0029
IL_0022: ldloc.0
IL_0023: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_0028: nop
IL_0029: endfinally
} // end handler

可以看到调用了SqlConnection的Dispose方法释放了资源。

本人声明: 个人主页:沐海(http://www.cnblogs.com/mahaisong) 以上文章都是经过本人设计实践和阅读其他文档得出。如果需要探讨或指教可以留言或加我QQ!欢迎交流!
原文地址:https://www.cnblogs.com/mahaisong/p/2025002.html