C# .NET - Problem in console application - Asked By balaram krishna on 21-Jan-10 11:54 PM


I designed one console application(Eg: test) in c# windows mobile. It's Working fine.
Now My problem is i am running the Exe file(test.exe) its showig the output.If  i selected the Exe(test.exe)
again it is starting another new process for the same file in task manager. But i want to use it like a single process even the
user is selected the exe file n number of times How to do it?????

re - Santhosh N replied to balaram krishna on 22-Jan-10 12:11 AM

you can make use of mutex for accomplishing this ..

A mutex is a synchronization primitive provided by the operating system that allows for interthread and interprocess communication. A mutex is typically used to protect a shared resource, providing exclusive access to it

you can check http://msdn.microsoft.com/en-us/magazine/cc163741.aspx for more info on this

And http://www.codeproject.com/KB/cs/CSSIApp.aspxone as well with a different approach

Use this - Kalit Sikka replied to balaram krishna on 22-Jan-10 01:13 AM

add dispose method in your code and use below method:

FindAndKillProcess(test.exe); // Passing name of process here

// Method to kill the process
public static bool FindAndKillProcess(string name)
        foreach (Process clsProcess in Process.GetProcesses()) {
                if (clsProcess.ProcessName.StartsWith(name))
                        return true;
        //process not found, return false
        return false;

Re - Naresh Kumar replied to balaram krishna on 22-Jan-10 01:51 AM

Check the process is already running in the task bar in your code, if the process is running exit the application. Otherwise you can execute the code.
using System.Diagnostics;
Process[] processlist = Process.GetProcesses();
foreach (Process theprocess in processlist)
                if (theprocess.ProcessName == "OUTLOOK")
Re - Huggy Bear replied to balaram krishna on 25-Jan-10 04:22 AM
You can achieve it with the following code in your Main method of your Console Application
static void Main(string[] args)
    bool isFirstInstance = true;
    //Check whether an instance running already
    Mutex mutex = new Mutex(true, "CurrentInstance", out isFirstInstance);
    //If not first instance, then just reutn the control and do not process further
    if (!isFirstInstance)
        //Continue the workflow and this is your first instance

Note: This will hold good, but the console window will get opened and closed if the instance is not the first one. This is the default behaviour and there is no direct way of suppressing this window. If you use the same logic for Windows it will not open any window becaause you will do the validation before the Application.Run is executed.