Solved

C# Singleton

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…

772 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