public class ClassA:IDisposable
{
#region IDisposable Members
public void Dispose()
{
GC.SuppressFinalize(this);
}
#endregion
}
public void fn_Data()
{
using (ClassA ObjectName = new ClassA())
{
// Use objectName
}
}
using
关键字有两种用法,具体如下。
As a directive
Generally we use the using
keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces and abstract classes and their methods and properties in the current page.
Example:
using System.IO;
As a statement
This is another way to use the using
keyword in C#. It plays a vital role in improving performance in garbage collection.
The using
statement ensures that Dispose() is called even if an exception occurs when you are creating objects and calling methods, properties and so on. Dispose() is a method that is present in the IDisposable interface that helps to implement custom garbage collection. In other words if I am doing some database operation (Insert, Update, Delete) but somehow an exception occurs then here the using statement closes the connection automatically. No need to call the connection Close() method explicitly.
Another important factor is that it helps in Connection Pooling. Connection Pooling in .NET helps to eliminate the closing of a database connection multiple times. It sends the connection object to a pool for future use (next database call). The next time a database connection is called from your application the connection pool fetches the objects available in the pool. So it helps to improve the performance of the application. So when we use the using statement the controller sends the object to the connection pool automatically, there is no need to call the Close() and Dispose() methods explicitly.
You can do the same as what the using statement is doing by using try-catch block and call the Dispose() inside the finally block explicitly. But the using statement does the calls automatically to make the code cleaner and more elegant. Within the using block, the object is read-only and cannot be modified or reassigned.
Example:
string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
}
}
using
语句(如using (SqlConnection conn = new SqlConnection(connString)
)和SqlDataReader对象也是如此,因此using
语句将自动调用conn.Close()方法,并且如果发生任何异常,它也会自动关闭连接。
有关更多信息,请参见使用和重要性在C#中的Using。
使用ADO.NET时,您可以使用关键字来定义连接对象或读取器对象等。这样在代码块完成后,它将自动释放您的连接。
IDisposable
接口的局部变量时, 一定 要使用using
1,没有例外。IDisposable
变量,则始终要实现IDisposable
模式。1):唯一的例外是——当您处理异常时。此时在finally
块中显式调用Dispose
可能会少些代码。
using关键字用于在使用资源后自动释放资源。
例如,如果您分配了一个文件资源,并且只需要在代码的一部分进行一些读写操作,那么使用 using 可以帮助您立即释放该文件资源。
被使用的资源需要实现 IDisposable 接口才能正常工作。
示例:
using (File file = new File (parameters))
{
// Code to do stuff with the file
}
using关键字定义对象的范围,当范围完成后处理该对象。例如:
using (Font font2 = new Font("Arial", 10.0f))
{
// Use font2
}
请点击此处查看有关C# using 关键字的MSDN文章。
另一个合理使用的例子是立即处理对象:
using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString))
{
while (myReader.Read())
{
MyObject theObject = new MyObject();
theObject.PublicProperty = myReader.GetString(0);
myCollection.Add(theObject);
}
}