Most implementations i've seen containing unmanaged resources end within a method's scope. I'm looking for ways to hold such a resource indefinitely and dispose it as the program stops running. An example of a resource which would quite possibly need to be used this way is CancellationTokenSource.Dispose().
One example would be to use a Destructor: Pass the resources in as dependencies and dispose them at container's last usage. This is feasible in, for instance, Windows Presentation Foundation programs (where the structure has been laid out like this by default) but rewriting the dependency construction for every new unmanaged resource is tiring. As the program scales, so does the distance traveled by the dependency.
A solution could be, to make every class where it's needed, disposable but isn't there a performance cost to liberal use of destructors?
My question to you: creative / uncommon ways of writing this specification. If you have learned the pros and cons of presented methods, please do weigh in anyway!
here's an example WPF program's App.xaml.cs
public partial class App : Application
{
UnmanagedDependency unmanagedDependency = new UnmanagedDependency();
public App()
{
MainWindow = new MainWindow (unmanagedDependency); //rewrite the constructor of MainWindow
MainWindow.Show();
}
~App() //destructor method; called when the object is no longer referenced
{
unmanagedDependency.Dispose();
}
}
Afterword: to clarify, my example type UnmanagedDependency
is not a wrapper class.