简体   繁体   中英

c# Using keyword usage in managed and unmanaged resources

The using keyword is used for properly disposing managed as well as unmanaged resources.

I am confused on when to use the using keyword.

For example using is used for managed resources such as the Connection object.

It is used for unmanaged resources such as below:

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

Is there a general rule of thumb when to use the using keyword? Should it be used for all objects so they are disposed of properly? How can you tell for which objects are prime candidates for the using keyword?

Is there a general rule of thumb when to use the using?

You should use it on any class that implements IDisposable , regardless of whether the resources are managed or unmanaged.

From MSDN :

As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

Usually , you should use it when a class implements IDisposable . However, there are some edge cases when to avoid it such as when you're using WCF, as explained here . Also, if you need to access the object somewhere else in the class, you can't use using because it limits the object's scope and so you should dispose your objects explicitly.

My general rule of thumb: If it can be used, use it.

When can it be used? In short, when the object implements IDisposable and you are done using it by the time your method is over.

A notable exception is web service clients (eg to WCF services) - the default implementation can result in the real error messages being lost. (eg see http://www.codeproject.com/Tips/197531/Do-not-use-using-for-WCF-Clients )

The using keyword like you are describing above will simply call Dispose on font1 when it goes out of scope.

Allthough there will probably exceptions, I think you are safe to assume that when a class implements IDisposable, you should call Dispose when you are done with the object.

The construction shown above will do that for you. In other situations you might not be able to use using as the lifetime of the object exceeds that of the function in which you created it. In that case it is wise to Dispose it manually.

Kind regards, Marwijn.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM