What are Mutexes and when is it advisable to use this feature?

5

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

  • What are Mutexes?
  • When is it advisable to use class Mutex ?
  • The case shown above used in class Mutex is ideal for prevent the application from running more than once?
  • asked by anonymous 15.10.2018 / 16:24

    1 answer

    4
      

    What are Mutexes?

    The MUTual EXclusion engine is used in competing environments and is a way to prevent a resource from being accessed by more than one processing line at a time. It is mainly used to avoid the race condition to maintain an operation atomatic .

    It is a way of locking a resource, usually in memory. There are other similar mechanisms like the semaphore, for example, where I already gave an answer and I spoke superficially about Mutex . The Wikipedia article shows some.

    While any feature can not be accessed concurrently, it does not need a mechanism of this type, and it is often preferable to have some form so it is much simpler, even if you need to duplicate the feature. Creating a Mutex is not cheap, and every feature that can only be accessed with a query to Mutex has much more expensive access than normal, in some cases this control is more expensive than the access itself. But not all cases can have concurrent access eliminated, there are objects that need a consistent global state.

    There are cases that an object can have an internal Mutex, in others it can be used in an individualized way. The internal use can give more assurance that no access will be violated, but it obliges the object to have the cost of this control in all accesses, even when there is no competition.

    Mutex, in general, is an object that indicates whether the object is being accessed by some code at that time or not. So you always need to consult it to know if you can do something on the object. Failure to do so may result in problems if you try to access the object without care. You can only access the object freely if Mutex is released and this should only happen when the person who created it does.

    Only one processing line can own a Mutex for a resource.

    Understand the Mutex as a doorman who says who can enter or not in a place and he only lets in if the place is vacant. He knows environments where everyone wants to talk and only one can. Someone controls the microphone of who can speak at that time. This is Mutex. And specific case only who can say that another person can use the microphone is who is using. Only he can turn off the use and allow another person to start using it. The other person may be trying, but you do not have access to it while the other person is using it.

    In C # you can see the code for the class that implements Mutex . Or can see how it is in .NET Core as well different and need to follow the abstractions as each operating system is different.

      

    WhenisitadvisabletousetheMutexclass?

    Inessencewhathasalreadybeensaid.ThereareexamplesinlinksforanswersalreadypostedhereinSOptthatshowthis.

      

    IsthecaseshownaboveusedintheMutexclassidealtopreventtheapplicationfromrunningmorethanonce?

    IdonotthinkMutexisnecessary,youmayknowthattheapplicationisrunninginotherways,andthecostofitisusuallyalreadyquitehigh,Idonotneedalow-costmechanismlikeMutex.

    NormallyaMutexshouldlastverylittletimeunderpenaltyofcausing deadlocks .

        
    15.10.2018 / 17:06