5
I read about Mutexes and the class Mutex. However, I cannot understand clearly what Mutex is and what this class does.
Since 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 repeatedly).
An implementation I did 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 method Main()
and serves in thesis to verify if there is already an instance of the running application process. And it seems to me a little gambiarra =/
Behold:
static void Main()
{
if (ProcessoExecutando())
{
return;
}
//Inicia aplicação
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new AppMain());
}
However, the meaning of the class Mutex
this confused in my mind and my lack of knowledge in it can cause me to use this resource in the wrong way.
Therefore, I would like to have the doubts clarified below.
Doubts
- What are Mutexes?
- When it is advisable to use the class
Mutex
? - The case illustrated above the class used
Mutex
is ideal for prevent the application from being executed more than once?