- When Is Memory Released?
- IDisposable and the Dispose Design Pattern
- The C# "using" Syntax
- Conclusion
- References
The C# "using" Syntax
In Listing 4, I protected object access with a try...finally block to ensure that the CoolThing object was disposed of properly when it was no longer needed. Objects that allocate unmanaged resources should always be protected in this manner. It's such a commonly used construct that the C# development team extended the language to provide a shortcut syntax to express it; the code shown in Listing 6 has the same effect as the code in Listing 4.
Listing 6 The using Syntax
for (int i = 0; i <= 3; i++) { // allocate a Thing and use it using (CoolThing2 ct = new CoolThing2(i)) { // do stuff with the Thing Console.WriteLine("Hello from Thing {0}", ct.ThingNumber); // Thing goes out of scope here and can be released } }
In this context, using is a shortcut for try...finally...Dispose.
The sample program shown in Listing 7 includes this change, and uses the new CoolThing2 class.
Listing 7 AllocExample2.cs
using System; namespace AllocExample2 { class Class1 { [STAThread] static void Main(string[] args) { try { for (int i = 0; i <= 3; i++) { // allocate a Thing and use it using (CoolThing2 ct = new CoolThing2(i)) { // do stuff with the Thing Console.WriteLine("Hello from Thing {0}", ct.ThingNumber); // Thing goes out of scope here and can be released } } } catch (Exception e) { Console.WriteLine("Exception: {0}", e); } Console.WriteLine("Press Enter to exit program"); Console.ReadLine(); } } }
Always Dispose()
Every .NET Framework class that allocates or potentially allocates an unmanaged resource implements IDisposable and the Dispose design pattern. Because of the way that finalizers are implemented, you should always call Dispose() to release the unmanaged resources that these classes allocate, rather than wait for the garbage collector to call the finalizer. Remember, you can't guarantee when the finalizer will be called, so you could end up with the situation shown in the first example: out of resources because the garbage collector hasn't released the objects yet.