Search code examples
c#mutexwindows-task-schedulersingle-instance

Mutex fails to limit running applications to one


I am writing a program to format and aggregate data to make it processable for power automate. However, I just noticed that one of my applications is able to run more than once at the same time, even though I used a mutex to surpress that behaviour.

Here is the code:

//Some code
string mutexName = "MutexName";
bool newC;
Mutex mutex = new(true, mutexName, out newC);
if (!newC)
{
    return;
}
//Some code

I am using the windows task scheduler to automatically start it everyday to restart it when it crashes. At first it worked fine and didn't cause any issues. But since yesterday it suddenly starts to just ignore the application running twice. The pc is acting as a server and is running constantly.

Thanks in advance!


Solution

  • Ok, found a method for that. I am saving the state of the application to show it on a website I had to build, so now I just check for that state and kill the task if it has the turnedOn-state.

    Here the code (it's a bit long, since it contains a Config-Reader used to load different file paths, containing the states):

    On startup:

    ConfigReader configReader = new("filePath");
    if (!checkTurnedOff(configReader))
    {
        return;
    }
    

    checkTurnedOff():

    bool checkTurnedOff(ConfigReader configReader)
    {
        if (configReader.GetFileData("running").Split('=')[3].Contains("false"))
        {
            return true;
        }
        return false;
    }
    

    GetFileData():

    public string GetFileData(string key)
    {
        return File.ReadAllText(GetValue(key));
    }