0

Is it somehow possible that if I start my program like 10 times fast in a row, but only one at a time should do something. The other keep waiting that the working program is finished or stopped.

So in the end, if I open my program 10 times, all 10 programs should be working in a row, not simultaneously.

Is this possible in c#?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Nico.E
  • 82
  • 11
  • 2
    You could take a lock on a file on startup and make the application wait while the file is not available. The first that runs will lock the file and as soon as that one closes the following one will be able to get the lock – Camilo Terevinto May 28 '18 at 10:10
  • Usual pattern is to use a mutex, like described here: https://stackoverflow.com/q/229565/5311735. – Evk May 28 '18 at 10:13
  • It depends what you are doing inside that program. If you are working on some text files you use mutex to lock the file from another application instances. If you are working on database it's possible to make another type of lock. – tzm May 28 '18 at 10:15
  • Please google "c# single instance application", lotsa hits. You'd probably like the ones that tell you that this feature is built into the framework. – Hans Passant May 28 '18 at 10:21

2 Answers2

1

You can use a named EventWaitHandle to do this, for example:

using System;
using System.Threading;

namespace Demo
{
    static class Program
    {
        static void Main()
        {
            using (var waitHandle = new EventWaitHandle(true, EventResetMode.AutoReset, "MyHandleName"))
            {
                Console.WriteLine("Waiting for handle");
                waitHandle.WaitOne();

                try
                {
                    // Body of program goes here.
                    Console.WriteLine("Waited for handle; press RETURN to exit program.");
                    Console.ReadLine();
                }

                finally
                {
                    waitHandle.Set();
                }

                Console.WriteLine("Exiting program");
            }
        }
    }
}

Try running a few instances of this console app and watch the output.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
0

You can use system wide Mutex or system wide Semaphore. If you create Mutex or Semaphore with name it become visible for whole system - in other words it can be visible from other processes.

 Mutex syncMutex = new Mutex(false, "NAME OF MUTEX");
        try
        {
            if(!syncMutex.WaitOne(MUTEX_TIMEOUT))
            {
                //fail to get mutex
                return;
            }
            //mutex obtained do something....
        }
        catch(Exception ex)
        {
            //handle error
        }
        finally
        {                
             //release mutex
            syncMutex.ReleaseMutex();
        }
Zbych R
  • 1
  • 2