Solved

C# Singleton

Posted on 2016-08-25
2
42 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 32

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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

705 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

19 Experts available now in Live!

Get 1:1 Help Now