I read about Mutexes and the class Mutex . However, I can not clearly understand what Mutex really is and what this class does.
Being that I would like to know if I can use this feature to prevent my desktop application from running more than once (multiple instances of the same process in case the user opens the program repeated times).
One implementation I made was as follows:
private bool ProcessoExecutando()
{
var localizacao = Assembly.GetExecutingAssembly().Location;
FileSystemInfo systemInfo = new FileInfo(localizacao);
Mutex mutex = new Mutex(true, "Global\" + systemInfo.Name, out bool novoProcessoCriado);
if (novoProcessoCriado)
{
mutex.ReleaseMutex();
}
return !novoProcessoCriado;
}
This method is called in the Main()
method and serves in thesis to check if an instance of the running process of the application already exists. And it seems to me a little gambiarra = /
See:
static void Main()
{
if (ProcessoExecutando())
{
return;
}
//Inicia aplicação
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new AppMain());
}
However, the meaning of the Mutex
class is confusing in my mind, and my lack of knowledge in it can cause me to use this feature in the wrong way.
So, I would like to have the questions clarified below.
Questions
Mutex
? Mutex
is ideal for
prevent the application from running more than once?