Add the following code to prevent multiple instance of your app from running.

using System.Diagnostics;

        public static void Main(string[] args)
        {
                var currentProcess = Process.GetCurrentProcess();

                if (IsProcessAlreadyRunning(currentProcess.ProcessName))
                {
                    Console.WriteLine($"Another instance of this process {currentProcess.ProcessName} is already running.  Terminating this instance of the process.");
                    System.Threading.Thread.Sleep(5000);
                    return;
                }
        }

        static bool IsProcessAlreadyRunning(string processNameToCheck)
        {
            return Process.GetProcesses().ToList().Where(x => x.ProcessName == processNameToCheck).Count() > 1;
        }
Last modified: June 24, 2019

Author

Comments

Write a Reply or Comment