1

I am using c# windows application.

when my application is started up, i want to check the instances in the taskmanager for the same application. If any instances running already, shud kill the process and start the new one.

This is to make shure that only one instances of application is running.

Anuya
  • 8,082
  • 49
  • 137
  • 222

4 Answers4

1

To me that sounds really aggressive and is probably not the best idea.

Perhaps you want to maintain a single instance of your app.

Community
  • 1
  • 1
Sam Saffron
  • 128,308
  • 78
  • 326
  • 506
1

Here's a quick and dirty way to make sure only one instance of your program is running. The secret is using a Mutex.

[STAThread]
static void Main()                  
{
    bool ok;
    m = new System.Threading.Mutex(true, "YourNameHere", out ok);

    if (!ok)
    {
        MessageBox.Show("Another instance is already running.");
        return;
    }

    // Do some stuff here...

    GC.KeepAlive(m);                
}

This code tries to create a Mutex (mutual exclusion) with a certain name and if it can't create it then an instance of this program must already be running.

CalebHC
  • 4,998
  • 3
  • 36
  • 42
  • this code needs a bit of work, for one it does not handle abandoned mutexes – Sam Saffron Jul 13 '09 at 05:31
  • Yeah, you're right. I guess you could call the WaitOne method on the mutex and if it fails, catch the AbandonedMutexException error and handle things appropriately. That's not a real good solution either. Like I said, it's quick and dirty. :p – CalebHC Jul 13 '09 at 05:49
0
public Process[] ExistingProcesses()    
{
    string processName = Process.GetCurrentProcess().ProcessName;
    Process[] processes = Process.GetProcessesByName(processName);
    return processes;
}
Amadeus45
  • 1,228
  • 2
  • 17
  • 28
0

Rather than depending on process name, which can be defeated even accidentally by renaming the executable, the traditional way to check for an existing instance is to have a named handle, such as a mutex. During startup, check if it already exists, shutting down immediately if it does.

edit

I just read the question again and it sounds like you really want to kill the previous instance, not kill the new one. The closest I can remember seeing to that behavior is what Google Chrome does when you open a new window and the old one is unresponsive, but even that checks for the lack of response and then prompts the user. Killing the old process sounds a bit extreme. Are you sure that's what you want to do?

Steven Sudit
  • 19,391
  • 1
  • 51
  • 53