Mutex implements singleton

using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Diagnostics;

namespace ConsoleApp19
{
    internal class Program
    {
        static void Main(string[] args)
        {
            TestMutexSingleton();
        }
         
        static void TestMutexSingleton()
        {
            string name = Process.GetCurrentProcess().MainModule.ModuleName;
            using(Mutex mtx=new Mutex(false, name))
            {
                if(!mtx.WaitOne(5000,false))
                {
                    Console.WriteLine($"{DateTime.Now.ToString("O")},An Instance of the Application {name} is Already Running!Enter any key to exit.");
                    Console.ReadKey();
                    return;
                }
                Console.WriteLine($"{DateTime.Now.ToString("O")},{Process.GetCurrentProcess().MainModule.ModuleName},{Process.GetCurrentProcess().Id},{Thread.CurrentThread.ManagedThreadId}");
                Console.ReadLine();
            } 
        }
  }      
}

 

 

posted @ 2024-03-11 17:01  FredGrit  阅读(5)  评论(0编辑  收藏  举报