using 语法可以(应该)用作为实现 IDisposable 接口的任何对象定义一个范围的方法。使用 using 语句可以确保在发生异常时调用 Dispose 方法。
//the compiler will create a local variable
//which will go out of scope outside this context
using (FileStream fs = new FileStream(file, FileMode.Open))
{
//do stuff
}
或者你可以直接使用:
FileStream fs;
try{
fs = new FileStream();
//do Stuff
}
finally{
if(fs!=null)
fs.Dispose();
}
C#通过.NET Framework共同语言运行时(CLR)自动释放不再需要的对象所使用的内存。内存的释放是非确定性的;CLR决定执行垃圾收集时才会释放内存。然而,最好尽快释放有限资源,如文件句柄和网络连接。
using语句允许程序员指定使用资源的对象何时应该释放它们。提供给using语句的对象必须实现IDisposable接口。该接口提供了Dispose方法,该方法应释放对象的资源。
使用 using(){}
语法糖可以确保任何具有 IDisposable 接口的对象例如 SqlConnection, 在 using(){}
作用域之外被正确释放。
using(SqlConnection conn = new SqlConnection(connString))
{
//use connection
}
//shorter than
SqlConnection conn = new SqlConnection(connString)
try
{
//use connection
}
finally
{
conn.Dispose();
}
当打开流或数据库连接时,通常会使用它。
它的行为类似于 try { ... } finally { ... } 块。在 using 块之后,用括号实例化的 IDisposable 对象将被正确关闭。
using (Stream stream = new Stream(...))
{
}
这种使用方式与释放资源有关,只能与实现IDisposable接口的类结合使用。
示例:
using(SqlConnection conn = new SqlConnection(someConnectionString))
{
//Do some database stuff here
}
try
{
using (var svc = new ServiceReference.ServiceName())
{
throw new Exception("Testing");
}
}
catch (Exception ex)
{
// What exception is caught here?
}
如果隐式的Dispose调用抛出异常,那么catch块会捕获该异常,而不是在using块内抛出的异常。