Solved

C# Singleton

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

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

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

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…
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.
In this video, viewers will be given step by step instructions on adjusting mouse, pointer and cursor visibility in Microsoft Windows 10. The video seeks to educate those who are struggling with the new Windows 10 Graphical User Interface. Change Cu…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…

632 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