欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-10-31 10:21:58
static void MutexDemo2() { string assName = Assembly.GetEntryAssembly().FullName; bool createdNew; using (var mutex = new Mutex(false, assName, out cr... ......

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();
            }           
        }