5

I developed an application that is hosted in one server. Many users access to it via Remote Desktop connection, but sometimes I saw in the task manager that the same user has opened 2-x instances. I need prevent that the same user can't open multiple instances. But notice that the program can be opened multiple times by different users. Please forgive me my English. Thanks.

PS: I'm using Winforms and C#

Yuri Morales
  • 2,351
  • 4
  • 25
  • 52
  • You can easily get the list of running processes. Then take a look on this to get owner of the process: http://stackoverflow.com/questions/300449/how-do-you-get-the-username-of-the-owner-of-a-process – Dilshod Jun 18 '13 at 20:25
  • @Dilshod that may not be so easy if the user is not an administrator in the machine when using *Remote Desktop* – I4V Jun 18 '13 at 20:27

2 Answers2

2

You can create a mutex with the user's name.

bool b = true;
Mutex mutex = new Mutex(true, Environment.UserName.ToLowerInvariant() , out b);
if (!b) throw new InvalidOperationException("Another instance is running");
I4V
  • 34,891
  • 6
  • 67
  • 79
  • Clean solution, but is there any way to show the opened form that the user is trying to open again? – Yuri Morales Jun 18 '13 at 20:36
  • @ymorales Another question can get better feedbacks then my comments. – I4V Jun 18 '13 at 20:39
  • 1
    You should probably prefix the mutex name with @"Global\" to ensure that it's seen across all terminal server sessions rather than only within the current instance. And as zmbq points out, you should probably include the app's name to avoid collisions with other software that might use your code sample. – EricLaw Jun 18 '13 at 21:39
  • In which function of my C# application this should be placed? – Tak Jul 14 '20 at 07:33
1

The recommended way to see if another instance of your application is already running is to use a Mutex. See here for example.

Since you want to allow multiple instances of the application to run if different users run them, simply add the current user name to the mutex's name. For example, call the Mutex "MyApp"+Environment.UserName

Community
  • 1
  • 1
zmbq
  • 38,013
  • 14
  • 101
  • 171