Resource Cleanup

Garbage collection is a key responsibility of the runtime. Nevertheless, it is important to recognize that the garbage collection process centers on the code’s memory utilization. It is not about the cleaning up of file handles, database connection strings, ports, or other limited resources.

Finalizers

Finalizers allow developers to write code that will clean up a class’s resources. Unlike constructors that are called explicitly using the new operator, finalizers cannot be called explicitly from within the code. There is no new equivalent such as a delete operator. Rather, the garbage collector is responsible for calling a finalizer on an object instance. Therefore, developers cannot determine at compile time exactly when the finalizer will execute. All they know is that the finalizer will run sometime between when an object was last used and generally when the application shuts down normally. The deliberate injection of incertitude with the word “Generally” highlights the fact that finalizers might not execute. This possibility is obvious when you consider that a process might terminate abnormally. For instance, events such as the computer being turned off or a forced termination of the process, such as when debugging the process, will prevent the finalizer from running. However, with .NET Core, even under normal circumstances, finalizers may not get processed before the application shuts down. As we shall see in the next section, it thus may be necessary to take additional action to register finalization activities with other mechanisms.

note
You cannot determine at compile time exactly when the finalizer will execute.

The finalizer declaration is identical to the destructor syntax of C#’s predecessor—that is, C++. As shown in Listing 10.15, the finalizer declaration is prefixed with a tilde before the name of the class.

Listing 10.15: Defining a Finalizer
1. using System.IO;
2.  
3. public class TemporaryFileStream
4. {
5.     public TemporaryFileStream(string fileName)
6.     {
7.         File = new FileInfo(fileName);
8.         // For a preferable solution use FileOptions.DeleteOnClose.
9.         Stream = new FileStream(
10.             File.FullName, FileMode.OpenOrCreate,
11.             FileAccess.ReadWrite);
12.     }
13.  
14.     public TemporaryFileStream()
15.         : this(Path.GetTempFileName())
16.     { }
17.  
18.     // Finalizer
19.     ~TemporaryFileStream()
20.     {
21.         try
22.         {
23.             Close();
24.         }
25.         catch (Exception )
26.         {
27.             // Write event to logs or UI
28.             // ...
29.         }
30.     }
31.  
32.     public FileStream? Stream { getprivate set; }
33.     public FileInfo? File { getprivate set; }
34.  
35.     public void Close()
36.     {
37.         Stream?.Dispose();
38.         try
39.         {
40.             File?.Delete();
41.         }
42.         catch(IOException exception)
43.         {
44.             Console.WriteLine(exception);
45.         }
46.         Stream = null;
47.         File = null;
48.     }
49. }

Finalizers do not allow any parameters to be passed, so they cannot be overloaded. Furthermore, finalizers cannot be called explicitly—that is, only the garbage collector can invoke a finalizer. Access modifiers on finalizers are therefore meaningless, and as such, they are not supported. Finalizers in base classes will be invoked automatically as part of an object finalization call.

note
Finalizers cannot be called explicitly; only the garbage collector can invoke a finalizer.

Because the garbage collector handles all memory management, finalizers are not responsible for de-allocating memory. Rather, they are responsible for freeing up resources such as database connections and file handles—resources that require an explicit activity that the garbage collector doesn’t know about.

In the finalizer shown in Listing 10.15, we start by disposing of the FileStream. This step is optional because the FileStream has its own finalizer that provides the same functionality as Dispose(). The purpose of invoking Dispose() now is to ensure that it is cleaned up when TemporaryFileStream is finalized, since the latter is responsible for instantiating the former. Without the explicit invocation of Stream?.Dispose(), the garbage collector will clean it up independently from the TemporaryFileStream once the TemporaryFileStream object is garbage collected and releases its reference on the FileStream object. That said, if we didn’t need a finalizer for resource cleanup anyway, it would not make sense to define a finalizer just for invoking FileStream.Dispose(). In fact, limiting the need for a finalizer to only objects that need resource cleanup that the runtime isn’t already aware of (resources that don’t have finalizers) is an important guideline that significantly reduces the number of scenarios where it is necessary to implement a finalizer.

In Listing 10.15, the purpose of the finalizer is to delete the file9—an unmanaged resource in this case. Hence we have the call to File?.Delete(). Now, when the finalizers are executed, the file will get cleaned up.

Finalizers execute on an unspecified thread, making their execution even less deterministic. This indeterminate nature makes an unhandled exception within a finalizer (outside of the debugger) likely to crash the application—and the source of this problem is difficult to diagnose because the circumstances that led to the exception are not clear. From the user’s perspective, the unhandled exception will be thrown relatively randomly and with little regard for any action the user was performing. For this reason, you should take care to avoid exceptions within finalizers. Instead, you should use defensive programming techniques such as checking for null (refer to the use of the null-conditional operator in Listing 10.15). In fact, it is advisable to catch all exceptions in the finalizer and report them via an alternative means (such as logging or via the user interface) rather than keeping them as unhandled exceptions. This guideline leads to the try/catch block surrounding the Delete() invocation.

Another potential option to force finalizers to execute is to invoke System.GC.WaitForPendingFinalizers(). When this method is invoked, the current thread will be suspended until all finalizers for objects that are no longer referenced have executed.

Deterministic Finalization with the using Statement

The problem with finalizers on their own is that they don’t support deterministic finalization (the ability to know when a finalizer will run). Rather, finalizers serve the important role of being a backup mechanism for cleaning up resources if a developer using a class neglects to call the requisite cleanup code explicitly.

For example, consider the TemporaryFileStream, which includes not only a finalizer but also a Close() method. This class uses a file resource that could potentially consume a significant amount of disk space. The developer using TemporaryFileStream can explicitly call Close() to restore the disk space.

Providing a method for deterministic finalization is important because it eliminates a dependency on the indeterminate timing behavior of the finalizer. Even if the developer fails to call Close() explicitly, the finalizer will take care of the call. In such a case, the finalizer will run later than if it was called explicitly.

Because of the importance of deterministic finalization, the base class library includes a specific interface for the pattern and C# integrates the pattern into the language. The IDisposable interface defines the details of the pattern with a single method called Dispose(), which developers call on a resource class to “dispose” of the consumed resources. Listing 10.16 demonstrates the IDisposable interface and some code for calling it.

Listing 10.16: Resource Cleanup with IDisposable
1. using System;
2. using System.IO;
3.  
4. public static class Program
5. {
6.     // ...
7.     public static void Search()
8.     {
9.         TemporaryFileStream fileStream =
10.             new();
11.  
12.         // Use temporary file stream
13.         // ...
14.  
15.         fileStream.Dispose();
16.  
17.         // ...
18.     }
19. }
20.  
21. class TemporaryFileStream : IDisposable
22. {
23.     public TemporaryFileStream(string fileName)
24.     {
25.         File = new FileInfo(fileName);
26.         Stream = new FileStream(
27.             File.FullName, FileMode.OpenOrCreate,
28.             FileAccess.ReadWrite);
29.     }
30.  
31.     public TemporaryFileStream()
32.         : this(Path.GetTempFileName()) { }
33.  
34.     ~TemporaryFileStream()
35.     {
36.         Dispose(false);
37.     }
38.  
39.     public FileStream? Stream { getprivate set; }
40.     public FileInfo? File { getprivate set; }
41.  
42.     #region IDisposable Members
43.     public void Dispose()
44.     {
45.         Dispose(true);
46.  
47.         //unregister from the finalization queue.
48.         System.GC.SuppressFinalize(this);
49.     }
50.     #endregion
51.     public void Dispose(bool disposing)
52.     {
53.         // Do not dispose of an owned managed object (one with a 
54.         // finalizer) if called by member finalize,
55.         // as the owned managed objects finalize method 
56.         // will be (or has been) called by finalization queue 
57.         // processing already
58.         if (disposing)
59.         {
60.             Stream?.Dispose();
61.         }
62.         try
63.         {
64.             File?.Delete();
65.         }
66.         catch (IOException exception)
67.         {
68.             Console.WriteLine(exception);
69.         }
70.         Stream = null;
71.         File = null;
72.     }
73. }

From Program.Search(), there is an explicit call to Dispose() after using the TemporaryFileStream. Dispose() is the method responsible for cleaning up the resources (in this case, a file) that are not related to memory and therefore are subject to cleanup implicitly by the garbage collector. Nevertheless, the execution here contains a hole that would prevent execution of Dispose()—namely, the chance that an exception will occur between the time when TemporaryFileStream is instantiated and the time when Dispose() is called. If this happens, Dispose() will not be invoked and the resource cleanup will have to rely on the finalizer. To avoid this problem, callers need to implement a try/finally block. Instead of requiring programmers to code such a block explicitly, C# provides a using statement expressly for the purpose (see Listing 10.17).

Listing 10.17: Invoking the using Statement
1. public static class Program
2. {
3.     public static void Search()
4.     {
5.         // C# 8.0
6.         using TemporaryFileStream fileStream1 = new();
7.  
8.         // Prior to C# 8.0
9.         using (TemporaryFileStream fileStream2 =
10.             new(),
11.             fileStream3 = new())
12.         {
13.             // Use temporary file stream;
14.         }
15.     }
16. }

In the first highlighted code snippet, the resultant CIL code is identical to the code that would be created if the programmer specified an explicit try/finally block, where fileStream.Dispose() is called in the finally block. The using statement, however, provides a syntax shortcut for the try/finally block.

Within this using statement, you can instantiate more than one variable by separating each variable from the others with a comma. The key considerations are that all variables must be of the same type, the type must implement IDisposable, and initialization occurs at the time of declaration. To enforce the use of the same type, the data type is specified only once rather than before each variable declaration.

C# 8.0 introduces a potential simplification with regard to resource cleanup. As shown in the second highlighted snippet of Listing 10.17, you can prefix the declaration of a disposable resource (one that implements IDisposable) with the using keyword. As is the case with the using statement, this will generate the try/finally behavior, with the finally block placed just before the variable goes out of scope (in this case, before the closing curly brace of the Search() method). One additional constraint on the using declaration is that the variable is read-only, so it can’t be assigned a different value.

Garbage Collection, Finalization, and IDisposable

There are several additional noteworthy items to point out in Listing 10.16. First, the IDisposable.Dispose() method contains an important call to System.GC.SuppressFinalize(). Its purpose is to remove the TemporaryFileStream class instance from the finalization (f-reachable) queue. This is possible because all cleanup was done in the Dispose() method rather than waiting for the finalizer to execute.

Without the call to SuppressFinalize(), the instance of the object will be included in the f-reachable queue—a list of all the objects that are mostly ready for garbage collection, except they also have finalization implementations. The runtime cannot garbage-collect objects with finalizers until after their finalization methods have been called. However, garbage collection itself does not call the finalization method. Rather, references to finalization objects are added to the f-reachable queue and are processed by an additional thread at a time deemed appropriate based on the execution context. In an ironic twist, this approach delays garbage collection for the managed resources—when it is most likely that these very resources should be cleaned up earlier. The reason for the delay is that the f-reachable queue is a list of “references”; as such, the objects are not considered garbage until after their finalization methods are called and the object references are removed from the f-reachable queue.

note
Objects with finalizers that are not explicitly disposed will end up with an extended object lifetime. Even after all explicit references have gone out of scope, the f-reachable queue will have references, keeping the object alive until the f-reachable queue processing is complete.

For this reason, Dispose() invokes System.GC.SuppressFinalize. Invoking this method informs the runtime that it should not add this object to the finalization queue, but instead should allow the garbage collector to de-allocate the object when it no longer has any references (including any f-reachable references).

Second, Dispose() calls Dispose(bool disposing) with an argument of true. The result is that the Dispose() method on Stream is invoked (cleaning up its resources and suppressing its finalization). Next, the temporary file itself is deleted immediately upon calling Dispose(). This important call eliminates the need to wait for the finalization queue to be processed before cleaning up potentially expensive resources.

Third, rather than calling Close(), the finalizer now calls Dispose(bool disposing) with an argument of false. The result is that Stream is not closed (disposed) even though the file is deleted. The condition around closing Stream ensures that if Dispose(bool disposing) is called from the finalizer, the Stream instance itself will also be queued up for finalization processing (or possibly it would have already run depending on the order). Therefore, when executing the finalizer, objects owned by the managed resource should not be cleaned up, as this action will be the responsibility of the finalization queue.

Fourth, you should use caution when creating both a Close() type and a Dispose() method. It is not clear by looking at only the API that Close() calls Dispose(), so developers will be left wondering whether they need to explicitly call Close() and Dispose().

Fifth, to increase the probability that the functionality defined in the finalizer will execute before a process shuts down even in .NET Core, you should register the code with the AppDomain.CurrentDomain.ProcessExit event handler. Any finalization code registered with this event handler will be invoked, barring an abnormal process termination (discussed in the next section).

Guidelines
DO implement the dispose pattern on objects with resources that are scarce or expensive.
DO implement IDisposable to support possible deterministic finalization on classes with finalizers.
DO implement finalizer methods only on objects with resources that don't have finalizers but still require cleanup.
DO refactor a finalization method to call the same code as IDisposable, perhaps simply by calling the Dispose() method.
DO NOT throw exceptions from finalizer methods.
CONSIDER registering the finalization code with the AppDomain.ProcessExit to increase the probability that resource cleanup will execute before the process exits.
DO unregister any AppDomain.ProcessExit events during dispose.
DO call System.GC.SuppressFinalize() from Dispose() to avoid repeating resource cleanup and delaying garbage collection on an object.
DO ensure that Dispose() is idempotent (it should be possible to call Dispose() multiple times).
DO keep Dispose() simple, focusing on the resource cleanup required by finalization.
AVOID calling Dispose() on owned objects that have a finalizer. Instead, rely on the finalization queue to clean up the instance.
AVOID referencing other objects that are not being finalized during finalization.
DO invoke a base class’s Dispose() method when overriding Dispose().
CONSIDER ensuring that an object becomes unusable after Dispose() is called. After an object has been disposed, methods other than Dispose() (which could potentially be called multiple times) should throw an ObjectDisposedException.
DO implement IDisposable on types that own disposable fields (or properties) and dispose of those instances.
DO invoke a base class’s Dispose() method from the Dispose(bool disposing) method if one exists.
Language Contrast: C++—Deterministic Destruction

Although finalizers are similar to destructors in C++, the fact that their execution cannot be determined at compile time makes them distinctly different. The garbage collector calls C# finalizers sometime after they were last used but before the program shuts down; C++ destructors are automatically called when the object (not a pointer) goes out of scope.

Although running the garbage collector can be a relatively expensive process, the fact that garbage collection is intelligent enough to delay running until process utilization is somewhat reduced offers an advantage over deterministic destructors, which will run at compile-time–defined locations, even when a processor is in high demand.

AdVanced Topic
Forcing Resource Cleanup before Process Exit

Starting with .NET Core, the finalizers may not execute when a process is shutting down. To increase the likelihood of execution, the finalization activities should be registered to execute when the process10 shuts down. For this reason, notice the statement involving ProcessExit in the SampleUnmanagedResource constructor in Listing 10.18, with Output 10.3 showing the result when no arguments are passed to the program. (The code involves LINQ, event registration, and special attributes,11 which aren’t covered until Chapters 12, 14, and 18, respectively.)

Listing 10.18: Registering with Process Exit
1. using System.IO;
2. using System.Linq;
3. using System.Runtime.CompilerServices;
4. using static ConsoleLogger;
5.  
6. public static class Program
7. {
8.     public static void Main(string[] args)
9.     {
10.         WriteLine("Starting...");
11.         DoStuff();
12.         if (args.Any(arg => arg.ToLower() == "-gc"))
13.         {
14.             GC.Collect();
15.             GC.WaitForPendingFinalizers();
16.         }
17.         WriteLine("Exiting...");
18.     }
19.  
20.     public static void DoStuff()
21.     {
22.         // ...
23.         
24.         WriteLine("Starting...");
25.         SampleUnmanagedResource? sampleUnmanagedResource = null;
26.  
27.         try
28.         {
29.             sampleUnmanagedResource =
30.                 new SampleUnmanagedResource();
31.             // Use unmanaged Resource
32.             // ...
33.         }
34.         finally
35.         {
36.             if (Environment.GetCommandLineArgs().Any(
37.             arg => arg.ToLower() == "-dispose"))
38.             {
39.                 sampleUnmanagedResource?.Dispose();
40.             }
41.         }
42.  
43.         WriteLine("Exiting...");
44.  
45.         // ...
46.     }
47. }
48.  
49. class SampleUnmanagedResource : IDisposable
50. {
51.     public SampleUnmanagedResource(string fileName)
52.     {
53.         WriteLine("Starting...",
54.             $"{nameof(SampleUnmanagedResource)}.ctor");
55.  
56.         WriteLine("Creating managed stuff...",
57.             $"{nameof(SampleUnmanagedResource)}.ctor");
58.         WriteLine("Creating unmanaged stuff...",
59.             $"{nameof(SampleUnmanagedResource)}.ctor");
60.  
61.         WeakReference<IDisposable> weakReferenceToSelf =
62.              new(this);
63.         ProcessExitHandler = (_, __) =>
64.         {
65.             WriteLine("Starting...""ProcessExitHandler");
66.             if (weakReferenceToSelf.TryGetTarget(
67.                 out IDisposable? self))
68.             {
69.                 self.Dispose();
70.             }
71.             WriteLine("Exiting...""ProcessExitHandler");
72.         };
73.         AppDomain.CurrentDomain.ProcessExit
74.             += ProcessExitHandler;
75.         WriteLine("Exiting...",
76.             $"{nameof(SampleUnmanagedResource)}.ctor");
77.     }
78.  
79.     // Stores the process exit delegate so that we can remove it
80.     // if Dispose() or Finalize() is called already.
81.     private EventHandler ProcessExitHandler { get; }
82.  
83.     public SampleUnmanagedResource()
84.         : this(Path.GetTempFileName()) { }
85.  
86.     ~SampleUnmanagedResource()
87.     {
88.         WriteLine("Starting...");
89.         Dispose(false);
90.         WriteLine("Exiting...");
91.     }
92.  
93.     public void Dispose()
94.     {
95.         Dispose(true);
96.         // ...
97.     }
98.  
99.     public void Dispose(bool disposing)
100.     {
101.         WriteLine("Starting...");
102.  
103.         // Do not dispose of an owned managed object (one with a 
104.         // finalizer) if called by member finalize,
105.         // as the owned managed objects finalize method 
106.         // will be (or has been) called by finalization queue 
107.         // processing already
108.         if (disposing)
109.         {
110.             WriteLine("Disposing managed stuff...");
111.         }
112.  
113.         AppDomain.CurrentDomain.ProcessExit -=
114.             ProcessExitHandler;
115.  
116.         WriteLine("Disposing unmanaged stuff...");
117.  
118.         WriteLine("Exiting...");
119.     }
120. }
Output 10.3
Main: Starting...
DoStuff: Starting...
SampleUnmanagedResource.ctor: Starting...
SampleUnmanagedResource.ctor: Creating managed stuff...
SampleUnmanagedResource.ctor: Creating unmanaged stuff...
SampleUnmanagedResource.ctor: Exiting...
DoStuff: Exiting...
Main: Exiting...
ProcessExitHandler: Starting...
Dispose: Starting...
Dispose: Disposing managed stuff...
Dispose: Disposing unmanaged stuff...
Dispose: Exiting...
ProcessExitHandler: Exiting...

Ignoring the WriteLine() statements throughout, the code begins with an invocation of DoStuff(), which instantiates the SampleUnmanagedResource.

When instantiating SampleUnmanagedResource, we simulate the instantiation of both managed and unmanaged resources using simple WriteLine() invocations. Next, we declare a delegate—called a handler—that will execute when the process exits. The handler leverages a WeakReference to the SampleUnmanagedResource instance and invokes Dispose() on the instance if there is still an instance to invoke. The WeakReference is necessary to ensure that ProcessExit doesn’t maintain a reference to the instance, thereby preventing the garbage collector from cleaning up the unmanaged resource after it goes out of scope and finalization has run. The handler is registered with AppDomain.CurrentDomain.ProcessExit and saved into the ProcessExitHandler property. The latter step is necessary so that we can remove the handler from the AppDomain.CurrentDomain.ProcessExit event when Dispose() executes, rather than have Dispose() execute repeatedly and unnecessarily.

Back in the DoStuff() method, we check whether the command-line argument -Dispose is specified as an argument when starting the program. If it is, then Dispose() would be invoked and neither the finalizer nor the ProcessExit handler will get invoked. Upon the exit from DoStuff(), the instance of SampleUnmanagedResource no longer has a root reference. However, when the garbage collector runs, it sees the finalizer and adds the resource to the finalization queue.

When the process begins to shut down, and assuming neither Dispose() nor the finalizer has executed on the SampleUnmanagedResource instance as yet, the AppDomain.CurrentDomain.ProcessExit event fires and invokes the handler, which in turn invokes Dispose(). The key difference in the Dispose() method from Listing 10.16 is that we unregister from AppDomain.CurrentDomain.ProcessExit so that Dispose() doesn’t get invoked again during the process exit if it was invoked earlier.

Note that while you can invoke GC.Collect() followed by GC.WaitForPendingFinalizers() to force all finalizers for objects without root references to run, and you could theoretically even do this right before the process exits, doing so is fallible. The first caveat is that library projects can’t invoke these methods immediately before the process exits because there is no instance of Main(). The second caveat is that even simple things like static references will be root references, so that static object instances will not be cleaned up. For this reason, using the ProcessExit handler is the preferred approach.

AdVanced Topic
Exception Propagating from Constructors

Even when an exception propagates out of a constructor, the object is still instantiated, although no new instance is returned by the new operator. If the type defines a finalizer, the method will run when the object becomes eligible for garbage collection (providing additional motivation to ensure the finalize method can run on partially constructed objects). Also note that if a constructor prematurely shares its this reference, it will still be accessible even if the constructor throws an exception. Do not allow this scenario to occur.

AdVanced Topic
Resurrecting Objects

By the time an object’s finalization method is called, all references to the object have disappeared and the only step before garbage collection is running the finalization code. Even so, it is possible to add a reference inadvertently for a finalization object back into the root reference’s graph. In such a case, the re-referenced object will no longer be inaccessible; in turn, it will not be ready for garbage collection. However, if the finalization method for the object has already run, it will not run again unless it is explicitly marked for finalization (using the GC.ReRegisterFinalize() method).

Obviously, resurrecting objects in this manner is peculiar behavior, and you should generally avoid it. Finalization code should be simple and should focus on cleaning up only the resources that it references.

________________________________________

9. Listing 10.20 is somewhat a contrived example because there is a FileOptions.DeleteOnClose option when instantiating the FileStream, which triggers the file’s deletion when the FileStream closes.
10. Technically the app domain, at least for .NET Framework projects.
11. See the accompanying source code.
{{ snackbarMessage }}
;