user9145305
user9145305

Reputation:

How to call a Singleton's Destructor When Closing Console Application?

I am a little confused if my current application is doing what I require. I want to basically just create a Singleton and when the Console application is terminated, call the Destructor of the Singleton. I have it so the Console App will terminate when I hit ENTER, but I am not exactly sure if this is doing what I want. When I put a breakpoint in the Destructor, it gets hit ONLY when I do hit Enter. I just want to make sure what I am doing is correct and if not, how can I change it.

Here is my Singleton:

 public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
    public static Singleton Instance { get { return lazy.Value; } }
    private Singleton() { }
    ~Singleton()
    {
        Console.WriteLine("Destructor Called."); // Breakpoint here
    }
}

And in my Main:

    public static void Main(string[] args)
    {
        Singleton instance = Singleton.Instance;
        Console.ReadLine();
    }

EDIT: Got it working, thanks!

Upvotes: 0

Views: 1283

Answers (1)

Vaibhav Gawali
Vaibhav Gawali

Reputation: 119

You can't call destructor programmatically. It is always called by .NET CLR in garbage collection. However for your singleton, I would strongly discourage use of destructor.

Recommendation is to implement IDisposable interface, if you want to release any resources. Or any custom interface implementation will work as well to release any resources, because its weird to implement IDisposable on Singleton.

public sealed class Singleton : IDisposable
{
    private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
    public static Singleton Instance { get { return lazy.Value; } }
    private Singleton() { }
    ~Singleton()
    {
        Console.WriteLine("Destructor Called."); // Breakpoint here
    }

    void IDisposable.Dispose()
    {
        Console.WriteLine("Dispose Called.");
        GC.SuppressFinalize(this);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Singleton.Instance.ToString();
        ((IDisposable)Singleton.Instance).Dispose();
        GC.Collect();
    }
}

Upvotes: 2

Related Questions