我应该在c#中什么时候使用“using”块?(复制)

时间:2022-09-10 23:43:41

This question already has an answer here:

这个问题已经有了答案:

Are there particular instances where I should (or shouldn't?) be using "using" blocks:

我是否应该(或不应该)使用“使用”块:

using(SomeType t = new SomeType()){
    ...
}

14 个解决方案

#1


84  

When the SomeType class implements IDisposable.

当SomeType类实现IDisposable时。

#2


79  

Some objects need some action to be taken when you have finished with them. Usually this is because the object uses some kind of resource that needs to be disposed of. For example, if you have a file object of class File, and this object opens a file from the file system, the file in the file system will need to be closed again.

当你完成一些对象时,需要采取一些行动。通常这是因为对象使用了某种需要处理的资源。例如,如果您有一个类文件的文件对象,并且这个对象从文件系统打开一个文件,那么文件系统中的文件将需要再次关闭。

If you just left the file object, and forgot to call file.Close() it wouldn't be cleaned up until the Garbage Collector (GC) ran and worked out nothing was still using the file object. When the Garbage Collector runs should be left to the Common Language Runtime (CLR) to decide. If the GC doesn't run for quite a while after you have finished with the file, the file could remain open potentially for a long time. This can pose a big problem if there are many file objects, or if something wants to open a file, but can't because the file object you left is still hanging around.

如果您只是离开了file对象,并且忘记调用file. close(),那么在垃圾收集器(GC)运行并计算出没有任何东西仍然在使用file对象之前,不会清理它。当垃圾收集器运行时,应该由公共语言运行时(CLR)决定。如果在完成该文件之后GC没有运行很长一段时间,那么该文件可能在很长一段时间内保持打开状态。如果有很多文件对象,或者有什么东西想要打开一个文件,但是不能这样做,因为您留下的文件对象仍然挂在那里。

To solve this problem, C# has the IDisposable interface. This has one method called Dispose. Classes that require some cleanup implement this Dispose method. This gives you a standard way for cleaning up any objects that use resources. There are a lot of classes that need to have Dispose called. The problem with this is that code gets covered with calls to Dispose, and they are tricky to follow because the place where you new'ed the object and call Dispose to clean it up are different. So, you had to look around the code a lot and be very careful to check there were calls to Dispose in the right place.

为了解决这个问题,c#有IDisposable接口。它有一个方法叫做Dispose。需要一些清理的类实现这个Dispose方法。这为您提供了一种标准的方法来清理使用资源的任何对象。有很多类需要调用Dispose。问题是,代码被调用处理,它们很棘手,因为您新创建的对象和调用Dispose来清理它的地方是不同的。因此,你必须仔细查看代码,并且非常小心地检查是否有调用在正确的地方处理。

To solve this problem C# introduced the 'using' keyword. You can put a 'using' keyword around where you new an object, and this ensures Dispose will be called on it for you. It guarantees that Dispose will be called whatever happens... even if there is an exception thrown within the body of the using statement.

为了解决这个问题,c#引入了“使用”关键字。您可以在新对象的周围放置一个“使用”关键字,这将确保Dispose将为您调用它。它保证无论发生什么,处置都会被称为……即使在using语句的主体中抛出异常。

So, you should use 'using' when you want to be sure an object that allocates resources will be cleaned up.

因此,当您希望确定分配资源的对象将被清理时,您应该使用“using”。


using can only be used for objects that are declared on the stack, i.e. in a function. It doesn't work for objects that are declared as members of a class. For them, you have to call Dispose yourself. You may have to implement Dispose in your class so that in can call Dispose on any member objects it has that require it.

使用只能用于在堆栈上声明的对象,例如在函数中。对于声明为类成员的对象,它不起作用。对他们来说,你得自己打电话。您可能需要在类中实现Dispose,以便in可以调用它拥有的任何需要它的成员对象Dispose。


Common objects that need using called on them are: Files, Database connections, Graphics objects such as Pen and Brush.

通常需要调用的对象有:文件、数据库连接、图形对象如钢笔和画笔。


Sometimes it is also used when you want two operations to happen together. For example if you want to write a log statement when a block of code is entered and when it exits you could write a log class that you could use like this:

有时,当您希望两个操作同时进行时,也可以使用它。例如,如果您想在输入代码块时编写日志语句,当代码块退出时,您可以编写一个日志类,您可以这样使用:

using( Log log = new Log("Doing stuff") )
{
    // Stuff
}

The constructor for the log class could be made to write out the message, and the Dispose method could also write it out. Implement the finalizer (~Log) to assert if the Dispose method doesn't get called to ensure the 'using' is remembered around the 'new Log'.

可以编写日志类的构造函数来编写消息,而Dispose方法也可以将其写出来。如果没有调用Dispose方法以确保在“新日志”周围记住“using”,则实现终结器(~Log)来断言。

#3


12  

Use using whenever the type implements IDisposable, unless you're going to wrap it in a try/catch block anyway, then you might as well (depending on what look you prefer) use a finally block.

使用类型实现IDisposable时,除非你打算用try/catch块来包装它,否则你也可以使用finally块(取决于你喜欢的外观)。

#4


10  

I see plenty of other answers indicated when you should have a using statement. I want to address when specifically should not have a using statement:

我看到很多其他的答案表明什么时候应该有一个使用语句。我想说明的是,具体什么时候不应该有使用声明:

If you need to use your object outside of the scope of the current function, don't have a using block. Good example are a factory method that returns a database connection or a method that needs to return a datareader. In either of those cases if you create your object with a using statement it would be disposed before the method returned, and therefore not usable outside the method.

如果需要在当前函数范围之外使用对象,则不要使用using块。一个很好的例子是返回数据库连接的工厂方法,或者需要返回datareader的方法。在这两种情况中,如果您使用using语句创建对象,它将在方法返回之前被处理,因此在方法之外不可用。

Now, you still want to be sure that those objects are disposed, so you still might want a using statement somewhere. Just don't include it in the method where the object is actually created. Instead, you can wrap the function call itself in a using statement.

现在,您仍然需要确保这些对象已被处理,因此您可能仍然需要某个地方的using语句。只是不要将它包含在实际创建对象的方法中。相反,可以将函数调用本身封装到一个using语句中。

#5


4  

When SomeType implements IDisposable.

当SomeType实现IDisposable。

That is a clue to you the developer that SomeType uses unmanaged resources that need to be cleaned up.

这向开发人员提供了一个线索,说明SomeType使用了需要清理的非托管资源。

#6


4  

Example:

例子:

        using(SqlConnection MyConnection = new SqlConnection("Connection string"))
        {
            MyConnection.Open();

            //...

            // 1. SQLConnection is a type that implements IDisposable
            // 2. So you can use MyConnection in a using statement
            // 3. When using block finishes, it calls Dispose method of 
            // SqlConnection class
            // 4. In this case, it will probably close the connection to 
            // the database and dispose MyConnection object

        }

You can create your own objects that implements IDisposable:

您可以创建自己的对象来实现IDisposable:

public class MyOwnObjectThatImplementsIDisposable : IDisposable
{

    //... some code

    public void Dispose()
    {
        // Put here the code you want to be executed when the
        // using statement finish.
    }
}

So you could use an object of MyOwnObjectThanImplementsIDisposable type in a using statement:

因此,可以在using语句中使用myownobjectimplementsidisposable类型的对象:

        using(MyOwnObjectThatImplementsIDisposable MyObject = new MyOwnObjectThatImplementsIDisposable)
        {

            // When the statement finishes, it calls the 
            // code you´ve writed in Dispose method
            // of MyOwnObjectThatImplementsIDisposable class
        }

Hope this helps

希望这有助于

#7


2  

In this context the using statement is handy for types that implement IDisposable. When the code block exits the scope of the using statement, Dispose() is called implicitly. It's a good habit when working with objects you want to dispose immediately after use.

在这个上下文中,use语句对于实现IDisposable的类型来说是很方便的。当代码块退出using语句的范围时,将隐式地调用Dispose()。使用后要立即处理的对象时,这是一个好习惯。

#8


2  

One specific instance in which you should be careful using a using block is with a WCF Service Client.

使用using块时应该小心的一个具体实例是WCF服务客户端。

As noted in this MSDN article, wrapping a WCF client (which does implement IDisposable) in a using block could mask any errors which result in the client being left in a faulted state (like a timeout or communication problem). Long story short, when Dispose() is called, the client's Close() method fires, but throws and error because it's in a faulted state. The original exception is then masked by the second exception. Not good.

正如本文中提到的,在using块中包装WCF客户机(它确实实现了IDisposable)可能会掩盖导致客户机处于故障状态(比如超时或通信问题)的任何错误。长话短说,当调用Dispose()时,客户机的Close()方法会触发,但会抛出并出错,因为它处于故障状态。然后,第一个异常被第二个异常所掩盖。不好的。

There are various workarounds out there, including one in the MSDN article itself. Others can be found at IServiceOriented and blog.davidbarret.net.

有各种各样的解决方案,包括MSDN文章本身中的一个。其他的可以在IServiceOriented和blog.davidbarret.net上找到。

I prefer the last method, myself.

我喜欢最后一种方法,我自己。

#9


2  

If you want a summary rule. Anytime an object using IDisposable where you would not have a catch, use using. Using, essentially, is this pattern:

如果你想要一个总结规则。任何时候,如果一个对象使用的是一次性的,你将不会有一个捕获,使用。从本质上讲,这一模式是:

try
{
  //instantiate and use object
}
finally
{
  //dispose object
}

If you do not need a catch, using can save you typing, which is a good thing.

如果你不需要接球,使用它可以节省你打字的时间,这是一件好事。

#10


1  

The primary rule is: * Use USING statement when objects implements IDisposable interface.

主要规则是:*在对象实现IDisposable interface时使用USING语句。

This interface provides the Dispose method, which should release the object's resources. If this method is not invoked then the object will stay in memory as long, as CLR wants to perform garbage collection. If the programmer use the USING statement then on the end the object will be disposed, and all resources will be free.

这个接口提供了Dispose方法,该方法应该释放对象的资源。如果不调用此方法,那么对象将在内存中停留很长时间,因为CLR希望执行垃圾收集。如果程序员使用USING语句,那么最终对象将被处理,所有的资源将被释放。

It is very important that all resources that are no longer in use be free as soon as possible.

非常重要的是,所有不再使用的资源都要尽快免费。

For more information about it just visit this link: microsoft

有关它的更多信息,请访问这个链接:微软

#11


1  

Maybe it is worth mentioning that underlying reason for adding “using” lo C# languge is following: some resources can be scarce enough that it doesn’t make sense to wait for GC to call IDisposable. For example, DB connections. If you use try/catch/finally you won’t end up with a dangling connection, but connection will be left hanging until GC doesn’t kick in and this can take a while (if you do not close it explicitly). IF you use "using" (excuse the pun) you will release the connection immediately even if you forgot to close it and even if some exception occured inside the using block.
Another reason, as previous post mentions, is that programmers do not always use finally to clean up. If not using finally in the case of exception you end up with leaking resources…

也许值得一提的是,添加“使用”lo c#语言的根本原因是:一些资源可能不够用,所以等待GC调用IDisposable是没有意义的。例如,数据库连接。如果您使用try/catch/最终您不会得到一个悬空连接,但是连接将被挂起,直到GC不启动,这可能需要一段时间(如果您不明确地关闭它)。如果您使用“using”(不好意思是双关语),您将立即释放连接,即使您忘记关闭它,即使在using块内部发生异常。另一个原因,正如前面提到的,是程序员不总是使用最后来清理。如果在异常情况下不使用finally,则会导致资源泄漏……

#12


0  

One situation is when you want to do something at the beginning of a code block, and then undo it at the end of the block, unconditionally (even if there is a throw).

一种情况是,当您想在代码块的开头做一些事情,然后在块的末尾无条件地撤销它(即使有抛出)。

The ctor for the disposable class that you build (and call within the using) would perform the action, and then the Dispose method would undo that action. This is typically how I use it.

构建的一次性类的ctor(并在use中调用)将执行该操作,然后Dispose方法将撤消该操作。这就是我通常使用它的方式。

#13


0  

Other people has mentioned about "IDisposable" already.

其他人已经提到了“IDisposable”。

But one of the caveats when using "using" statement is that, any exceptions thrown within "using" will not be caught even thought "SomeType" will be disposed regardless.

但是使用“using”语句时需要注意的一点是,在“using”语句中抛出的任何异常都不会被捕获,即使认为“SomeType”将被处理。

So in the following snippet,

在下面的代码片段中,

using (SomeType t = new SomeType()){
    throw new Exception("thrown within using");
}

throw new Exception("thrown within using"); should not be disregarded.

抛出新异常(“在使用中抛出”);不应该被忽视。

#14


0  

I would also add that use a using() statement if something implements IDispose and also if that something you want to dispose of holds on to NON-MANAGED resources like database connections and file handles.

我还将添加一个using()语句,如果实现了IDispose,如果您想要处理的对象保存到非托管资源(如数据库连接和文件句柄),则使用该语句。

If it's a normal object with say a List<T>, where T is like a Customer object that holds names and address, then you don't need to. The garbage collector is smart enough to manage this for you. But the garbage collector WILL NOT return connections to the connection pool or close file handles.

如果它是一个具有List 的普通对象,其中T就像一个保存名称和地址的客户对象,那么您不需要这样做。垃圾收集器非常聪明,可以为您管理这个。但是垃圾收集器不会返回到连接池的连接或关闭文件句柄。

#1


84  

When the SomeType class implements IDisposable.

当SomeType类实现IDisposable时。

#2


79  

Some objects need some action to be taken when you have finished with them. Usually this is because the object uses some kind of resource that needs to be disposed of. For example, if you have a file object of class File, and this object opens a file from the file system, the file in the file system will need to be closed again.

当你完成一些对象时,需要采取一些行动。通常这是因为对象使用了某种需要处理的资源。例如,如果您有一个类文件的文件对象,并且这个对象从文件系统打开一个文件,那么文件系统中的文件将需要再次关闭。

If you just left the file object, and forgot to call file.Close() it wouldn't be cleaned up until the Garbage Collector (GC) ran and worked out nothing was still using the file object. When the Garbage Collector runs should be left to the Common Language Runtime (CLR) to decide. If the GC doesn't run for quite a while after you have finished with the file, the file could remain open potentially for a long time. This can pose a big problem if there are many file objects, or if something wants to open a file, but can't because the file object you left is still hanging around.

如果您只是离开了file对象,并且忘记调用file. close(),那么在垃圾收集器(GC)运行并计算出没有任何东西仍然在使用file对象之前,不会清理它。当垃圾收集器运行时,应该由公共语言运行时(CLR)决定。如果在完成该文件之后GC没有运行很长一段时间,那么该文件可能在很长一段时间内保持打开状态。如果有很多文件对象,或者有什么东西想要打开一个文件,但是不能这样做,因为您留下的文件对象仍然挂在那里。

To solve this problem, C# has the IDisposable interface. This has one method called Dispose. Classes that require some cleanup implement this Dispose method. This gives you a standard way for cleaning up any objects that use resources. There are a lot of classes that need to have Dispose called. The problem with this is that code gets covered with calls to Dispose, and they are tricky to follow because the place where you new'ed the object and call Dispose to clean it up are different. So, you had to look around the code a lot and be very careful to check there were calls to Dispose in the right place.

为了解决这个问题,c#有IDisposable接口。它有一个方法叫做Dispose。需要一些清理的类实现这个Dispose方法。这为您提供了一种标准的方法来清理使用资源的任何对象。有很多类需要调用Dispose。问题是,代码被调用处理,它们很棘手,因为您新创建的对象和调用Dispose来清理它的地方是不同的。因此,你必须仔细查看代码,并且非常小心地检查是否有调用在正确的地方处理。

To solve this problem C# introduced the 'using' keyword. You can put a 'using' keyword around where you new an object, and this ensures Dispose will be called on it for you. It guarantees that Dispose will be called whatever happens... even if there is an exception thrown within the body of the using statement.

为了解决这个问题,c#引入了“使用”关键字。您可以在新对象的周围放置一个“使用”关键字,这将确保Dispose将为您调用它。它保证无论发生什么,处置都会被称为……即使在using语句的主体中抛出异常。

So, you should use 'using' when you want to be sure an object that allocates resources will be cleaned up.

因此,当您希望确定分配资源的对象将被清理时,您应该使用“using”。


using can only be used for objects that are declared on the stack, i.e. in a function. It doesn't work for objects that are declared as members of a class. For them, you have to call Dispose yourself. You may have to implement Dispose in your class so that in can call Dispose on any member objects it has that require it.

使用只能用于在堆栈上声明的对象,例如在函数中。对于声明为类成员的对象,它不起作用。对他们来说,你得自己打电话。您可能需要在类中实现Dispose,以便in可以调用它拥有的任何需要它的成员对象Dispose。


Common objects that need using called on them are: Files, Database connections, Graphics objects such as Pen and Brush.

通常需要调用的对象有:文件、数据库连接、图形对象如钢笔和画笔。


Sometimes it is also used when you want two operations to happen together. For example if you want to write a log statement when a block of code is entered and when it exits you could write a log class that you could use like this:

有时,当您希望两个操作同时进行时,也可以使用它。例如,如果您想在输入代码块时编写日志语句,当代码块退出时,您可以编写一个日志类,您可以这样使用:

using( Log log = new Log("Doing stuff") )
{
    // Stuff
}

The constructor for the log class could be made to write out the message, and the Dispose method could also write it out. Implement the finalizer (~Log) to assert if the Dispose method doesn't get called to ensure the 'using' is remembered around the 'new Log'.

可以编写日志类的构造函数来编写消息,而Dispose方法也可以将其写出来。如果没有调用Dispose方法以确保在“新日志”周围记住“using”,则实现终结器(~Log)来断言。

#3


12  

Use using whenever the type implements IDisposable, unless you're going to wrap it in a try/catch block anyway, then you might as well (depending on what look you prefer) use a finally block.

使用类型实现IDisposable时,除非你打算用try/catch块来包装它,否则你也可以使用finally块(取决于你喜欢的外观)。

#4


10  

I see plenty of other answers indicated when you should have a using statement. I want to address when specifically should not have a using statement:

我看到很多其他的答案表明什么时候应该有一个使用语句。我想说明的是,具体什么时候不应该有使用声明:

If you need to use your object outside of the scope of the current function, don't have a using block. Good example are a factory method that returns a database connection or a method that needs to return a datareader. In either of those cases if you create your object with a using statement it would be disposed before the method returned, and therefore not usable outside the method.

如果需要在当前函数范围之外使用对象,则不要使用using块。一个很好的例子是返回数据库连接的工厂方法,或者需要返回datareader的方法。在这两种情况中,如果您使用using语句创建对象,它将在方法返回之前被处理,因此在方法之外不可用。

Now, you still want to be sure that those objects are disposed, so you still might want a using statement somewhere. Just don't include it in the method where the object is actually created. Instead, you can wrap the function call itself in a using statement.

现在,您仍然需要确保这些对象已被处理,因此您可能仍然需要某个地方的using语句。只是不要将它包含在实际创建对象的方法中。相反,可以将函数调用本身封装到一个using语句中。

#5


4  

When SomeType implements IDisposable.

当SomeType实现IDisposable。

That is a clue to you the developer that SomeType uses unmanaged resources that need to be cleaned up.

这向开发人员提供了一个线索,说明SomeType使用了需要清理的非托管资源。

#6


4  

Example:

例子:

        using(SqlConnection MyConnection = new SqlConnection("Connection string"))
        {
            MyConnection.Open();

            //...

            // 1. SQLConnection is a type that implements IDisposable
            // 2. So you can use MyConnection in a using statement
            // 3. When using block finishes, it calls Dispose method of 
            // SqlConnection class
            // 4. In this case, it will probably close the connection to 
            // the database and dispose MyConnection object

        }

You can create your own objects that implements IDisposable:

您可以创建自己的对象来实现IDisposable:

public class MyOwnObjectThatImplementsIDisposable : IDisposable
{

    //... some code

    public void Dispose()
    {
        // Put here the code you want to be executed when the
        // using statement finish.
    }
}

So you could use an object of MyOwnObjectThanImplementsIDisposable type in a using statement:

因此,可以在using语句中使用myownobjectimplementsidisposable类型的对象:

        using(MyOwnObjectThatImplementsIDisposable MyObject = new MyOwnObjectThatImplementsIDisposable)
        {

            // When the statement finishes, it calls the 
            // code you´ve writed in Dispose method
            // of MyOwnObjectThatImplementsIDisposable class
        }

Hope this helps

希望这有助于

#7


2  

In this context the using statement is handy for types that implement IDisposable. When the code block exits the scope of the using statement, Dispose() is called implicitly. It's a good habit when working with objects you want to dispose immediately after use.

在这个上下文中,use语句对于实现IDisposable的类型来说是很方便的。当代码块退出using语句的范围时,将隐式地调用Dispose()。使用后要立即处理的对象时,这是一个好习惯。

#8


2  

One specific instance in which you should be careful using a using block is with a WCF Service Client.

使用using块时应该小心的一个具体实例是WCF服务客户端。

As noted in this MSDN article, wrapping a WCF client (which does implement IDisposable) in a using block could mask any errors which result in the client being left in a faulted state (like a timeout or communication problem). Long story short, when Dispose() is called, the client's Close() method fires, but throws and error because it's in a faulted state. The original exception is then masked by the second exception. Not good.

正如本文中提到的,在using块中包装WCF客户机(它确实实现了IDisposable)可能会掩盖导致客户机处于故障状态(比如超时或通信问题)的任何错误。长话短说,当调用Dispose()时,客户机的Close()方法会触发,但会抛出并出错,因为它处于故障状态。然后,第一个异常被第二个异常所掩盖。不好的。

There are various workarounds out there, including one in the MSDN article itself. Others can be found at IServiceOriented and blog.davidbarret.net.

有各种各样的解决方案,包括MSDN文章本身中的一个。其他的可以在IServiceOriented和blog.davidbarret.net上找到。

I prefer the last method, myself.

我喜欢最后一种方法,我自己。

#9


2  

If you want a summary rule. Anytime an object using IDisposable where you would not have a catch, use using. Using, essentially, is this pattern:

如果你想要一个总结规则。任何时候,如果一个对象使用的是一次性的,你将不会有一个捕获,使用。从本质上讲,这一模式是:

try
{
  //instantiate and use object
}
finally
{
  //dispose object
}

If you do not need a catch, using can save you typing, which is a good thing.

如果你不需要接球,使用它可以节省你打字的时间,这是一件好事。

#10


1  

The primary rule is: * Use USING statement when objects implements IDisposable interface.

主要规则是:*在对象实现IDisposable interface时使用USING语句。

This interface provides the Dispose method, which should release the object's resources. If this method is not invoked then the object will stay in memory as long, as CLR wants to perform garbage collection. If the programmer use the USING statement then on the end the object will be disposed, and all resources will be free.

这个接口提供了Dispose方法,该方法应该释放对象的资源。如果不调用此方法,那么对象将在内存中停留很长时间,因为CLR希望执行垃圾收集。如果程序员使用USING语句,那么最终对象将被处理,所有的资源将被释放。

It is very important that all resources that are no longer in use be free as soon as possible.

非常重要的是,所有不再使用的资源都要尽快免费。

For more information about it just visit this link: microsoft

有关它的更多信息,请访问这个链接:微软

#11


1  

Maybe it is worth mentioning that underlying reason for adding “using” lo C# languge is following: some resources can be scarce enough that it doesn’t make sense to wait for GC to call IDisposable. For example, DB connections. If you use try/catch/finally you won’t end up with a dangling connection, but connection will be left hanging until GC doesn’t kick in and this can take a while (if you do not close it explicitly). IF you use "using" (excuse the pun) you will release the connection immediately even if you forgot to close it and even if some exception occured inside the using block.
Another reason, as previous post mentions, is that programmers do not always use finally to clean up. If not using finally in the case of exception you end up with leaking resources…

也许值得一提的是,添加“使用”lo c#语言的根本原因是:一些资源可能不够用,所以等待GC调用IDisposable是没有意义的。例如,数据库连接。如果您使用try/catch/最终您不会得到一个悬空连接,但是连接将被挂起,直到GC不启动,这可能需要一段时间(如果您不明确地关闭它)。如果您使用“using”(不好意思是双关语),您将立即释放连接,即使您忘记关闭它,即使在using块内部发生异常。另一个原因,正如前面提到的,是程序员不总是使用最后来清理。如果在异常情况下不使用finally,则会导致资源泄漏……

#12


0  

One situation is when you want to do something at the beginning of a code block, and then undo it at the end of the block, unconditionally (even if there is a throw).

一种情况是,当您想在代码块的开头做一些事情,然后在块的末尾无条件地撤销它(即使有抛出)。

The ctor for the disposable class that you build (and call within the using) would perform the action, and then the Dispose method would undo that action. This is typically how I use it.

构建的一次性类的ctor(并在use中调用)将执行该操作,然后Dispose方法将撤消该操作。这就是我通常使用它的方式。

#13


0  

Other people has mentioned about "IDisposable" already.

其他人已经提到了“IDisposable”。

But one of the caveats when using "using" statement is that, any exceptions thrown within "using" will not be caught even thought "SomeType" will be disposed regardless.

但是使用“using”语句时需要注意的一点是,在“using”语句中抛出的任何异常都不会被捕获,即使认为“SomeType”将被处理。

So in the following snippet,

在下面的代码片段中,

using (SomeType t = new SomeType()){
    throw new Exception("thrown within using");
}

throw new Exception("thrown within using"); should not be disregarded.

抛出新异常(“在使用中抛出”);不应该被忽视。

#14


0  

I would also add that use a using() statement if something implements IDispose and also if that something you want to dispose of holds on to NON-MANAGED resources like database connections and file handles.

我还将添加一个using()语句,如果实现了IDispose,如果您想要处理的对象保存到非托管资源(如数据库连接和文件句柄),则使用该语句。

If it's a normal object with say a List<T>, where T is like a Customer object that holds names and address, then you don't need to. The garbage collector is smart enough to manage this for you. But the garbage collector WILL NOT return connections to the connection pool or close file handles.

如果它是一个具有List 的普通对象,其中T就像一个保存名称和地址的客户对象,那么您不需要这样做。垃圾收集器非常聪明,可以为您管理这个。但是垃圾收集器不会返回到连接池的连接或关闭文件句柄。