Solved

C# Singleton

Posted on 2016-08-25
2
80 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 34

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

How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

Question has a verified solution.

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

Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

734 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