Allow only one instance

0

How do I make my application run only 1 instance at a time?

void Main(string[] s){
//faz algo
}
    
asked by anonymous 12.12.2015 / 18:54

1 answer

0

I searched deeper in the libraries of Microsoft and encontei something like Mutex , and interpreted this code to keep only one instance.

using System.Threading;
namespace MeuNamespace
{
    class Program
    {
        static Mutex mutex = new Mutex(true, "MeuAplicativo");
        static void Main(string[] args)
        {
            if (mutex.WaitOne(TimeSpan.Zero, true))
            {
                // faz algo
                mutex.ReleaseMutex();
            }
            else
            {
                MessageBox.Show("Já tens uma instancia em execução!");
            }
        }
    }
}

OBS! Do not forget that you can not apply Mutex.ReleaseMutex directly. He should at least do something before it's released, if not just that the mutex is released before and generating an exception.

Source: link

Reference:

Mutex.WaitOne : Blocks the current thread until the current instance receives a signal, using a TimeSpan to specify the time interval and specifying whether to exit the synchronization domain before the wait time. (Inherited from WaitHandle.)

    
12.12.2015 / 18:54