How to implement a singleton pattern with an infinite loop - C #

I am currently working on a C # application that runs in an infinite loop with a Thread.Sleep call after each iteration of the other method calls. My main

static void Main(string[] args)
    {
        bool isOnlyInstance = false;
        Mutex mutex = new Mutex(true, "RiskMetricsSensitivitiesDatabaseLoader", out isOnlyInstance);

        if (!isOnlyInstance)
        {
            return;
        }

        while (true)
        {
            ProcessData();
            Thread.Sleep(MainLoopSleep);
        }

        GC.KeepAlive(mutex);
    }

I inserted a KeepAlive call at the end of the method to make sure that the singleton mutex works as expected, as described on different websites. The KeepAlive call must contain garbage collection in order to drop mutexes, since .NET is looking forward to anticipating / optimizing garbage collection.

, , KeepAlive , Thread.Sleep? , KeepAlive , , .

+3
2

Mutex . using?

using(new Mutex(blah, blah, blah)){
    while(true){
        Blah(blah);
    }
}

, , Mutex .

+10

. GC.KeepAlive , , . , , , .

+1

Source: https://habr.com/ru/post/1729942/


All Articles