C# Mutex to make sure only one unique application instance started

2022-10-13,,,,


static void mutexdemo2()
        {
            string assname = assembly.getentryassembly().fullname;
            bool creatednew;
            using (var mutex = new mutex(false, assname, out creatednew))
            {
                if (!creatednew)
                {
                    console.writeline("the app in running!");
                    console.readline();
                }
                else
                {
                    console.writeline("welcome!");
                    console.readline();
                }
            }
        }

 

using system;
using system.threading.tasks;
using system.reflection;
using system.threading;
using system.windows.forms;

 static void main(string[] args)
        {
            mutexdemobool();
            console.readline();
        }

        static void mutexdemo()
        {
            string assemblyname = assembly.getentryassembly().fullname;             
            var mutex = new mutex(false, assemblyname);

            if (!mutex.waitone(0, true))
            {
                messagebox.show("unable to run multiple instances of this program.", "error", messageboxbuttons.ok, messageboxicon.error);
            }
            else
            {
                console.writeline("welcome");
                console.readline();
            }            
        }

        static void mutexdemobool()
        {
            string assemblyname = assembly.getentryassembly().fullname;
            bool isfirstinstance;
            var mutex = new mutex(false, assemblyname,out isfirstinstance);
            if(!isfirstinstance)
            {
                messagebox.show("unable to run multiple instances of this program.", "error", messageboxbuttons.ok, messageboxicon.error);
            }
            else
            {
                console.writeline("welcome");
                console.readline();
            }           
        }

 

《C# Mutex to make sure only one unique application instance started.doc》

下载本文的Word格式文档,以方便收藏与打印。