Solved

C# Singleton

Posted on 2016-08-25
2
54 Views
Last Modified: 2016-08-25
I'm trying to implement Singleton in my application.  Basically, if my application is already opened I don't want another instance to open.
static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Singleton s = Singleton.Instance;
            if (s != null)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainForm());
            }
        }
    }

    public sealed class Singleton
    {
        private static Singleton instance = null;
        private static readonly object padlock = new object();

        Singleton()
        {
        }

        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                { 
                    lock(padlock)
                    {
                        if (instance == null)
                            instance = new Singleton();
                    }
                }
                return instance;
            }
        }

Open in new window

I tried changing the code to below but it's still not working.  Form is still opening up.
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new MainForm());
            Application.Run(Singleton.Instance.mainForm());
        }
    }

    public sealed class Singleton
    {
        private static Singleton instance = null;
        private static readonly object padlock = new object();
        MainForm _mainForm = new MainForm();

        Singleton()
        {
        }

        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (padlock)
                    {
                        if (instance == null)
                            instance = new Singleton();
                    }
                }
                return instance;
            }
        }

        public MainForm mainForm()
        {
            return _mainForm;
        }
    }

Open in new window

0
Comment
Question by:CipherIS
2 Comments
 
LVL 33

Accepted Solution

by:
ste5an earned 500 total points
ID: 41770500
First of all: This has nothing to do with the singleton pattern, where that name comes from. This patter ensures that on class is only instantiated only once in the same app domain.

Basically, if my application is already opened I don't want another instance to open.
Completely different task.

Create a named mutex, when starting your executable and release it afterwards.

E.g.
namespace ConsoleCS
{
    using System;
    using System.Threading;

    public class Program
    {
        public static void Main(string[] args)
        {
            bool owned = false;
            Mutex mutex = new Mutex(true, "1321321sdfsd1221ds", out owned);
            if (!owned) {
                Console.WriteLine("\nOther instance running.");
            }

            Console.WriteLine("\nDone.");
            Console.ReadLine();
        }
    }
}

Open in new window


in your case

        static void Main()
        {
            bool owned = false;
            Mutex mutex = new Mutex(true, "1321321sdfsd1221ds", out owned);
            if (owned)
            {
                try
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new MainForm());
                }
                finally
                {
                    mutex.ReleaseMutex();
                }
            }
        }

Open in new window


Where 1321321sdfsd1221ds is an application specific unique constant.
0
 
LVL 1

Author Closing Comment

by:CipherIS
ID: 41770525
Thanks.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
I designed this idea while studying technology in the classroom.  This is a semester long project.  Students are asked to take photographs on a specific topic which they find meaningful, it can be a place or situation such as travel or homelessness.…

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now