1

At some point during my application I want to save a file and if it fails to quit the app, display a fail reason AND free all unmanaged resources witch is done through the distructor.

While using the debug and step by step (F11) execution I have seen the distructor is not called in my code. Is the unmanaged resource freed or is there a way to also ensure that distructors are called in case the information cannot be saved and app must exit ?

public class MyClass()
{
  private UnmanagedResource unmanagedResource;

  MyClass()
  {
    unmanaged resource = new UnmanagedResource();
  }

  ~MyClass()
  {
    ((IDisposable)unmanagedResource).Dispose();
  }

  public save()
  {
    try
    {
      unamangedResource.Save();
    }
    catch (System.IO.IOException)
    {
      Console.WriteLine("Error saving");
      Environment.Exit(1);
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Ciprian Dragoe
  • 340
  • 2
  • 14

1 Answers1

1

When the process exits, then the operating system makes sure that all resources (memory, opened files, opened sockets, synchronization objects, etc) your process holds are freed. So there is no need to worry about leaking resources.

Still, terminating the whole application from some very specific functionality is not a good idea design-wise.

NineBerry
  • 26,306
  • 3
  • 62
  • 93