Link to home
Start Free TrialLog in
Avatar of dkilby
dkilbyFlag for Canada

asked on

c#.net application + check if already running

I have an application that runs automatically every few mins, sometimes it runs long and a new instance will try to start, how can i check if it is already running and if so just shut down the newest instance that started up leaving the original to still continue

thanks
SOLUTION
Avatar of Snarf0001
Snarf0001
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dkilby

ASKER

both these work - thank you - is there code that works best for stopping the instance that just started while leaving the other to still run ?
Avatar of Russ Suter
Russ Suter

It depends entirely on where your code execution is. Assuming this either a Windows Forms application or a console application I would expect your project has a file called Program.cs. In it there is typically a Main() function that looks something like this:
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new form1());
        }

Open in new window

You can simply wrap that 3rd line in a conditional statement to make it look like this:
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Process[] runningProcesses = Process.GetProcessesByName("myApplication");
            if (runningProcesses.Length == 0)
            {
                Application.Run(new form1());
            }
        }

Open in new window

if you are starting this process using task scheduler then simply check the checkbox to User generated image