views:

206

answers:

2

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

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 have inserted the KeepAlive call at the end of the method to ensure the singleton mutex works as expected, as outlined by various websites. The call to KeepAlive is supposed to keep garbage collection from throwing away the mutex, since .NET looks forward to anticipate/optimize garbage collection.

My question is, since the actual call to KeepAlive never gets reached, should I put it in the loop after Thread.Sleep? The compiler warns that KeepAlive never gets called, and I'm concerned that it will therefore ignore this line in my garbage collection prevention algorithm.

+8  A: 

Mutex is disposable. Why not wrap it in a using?

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

Note that this works without even assigning the new Mutex to a named variable.

P Daddy
+1. Good solution, and you even mention the alternative of using a static variable.
RichardOD
@RichardOD: Using a static variable is an alternative. I didn't mention it, though.
P Daddy
Quick Spider Man, use your common sense! By that I mean, thanks for the great idea.
Norla
@P Daddy. You're right. Somehow I misread "without even assigning the new Mutex to a named variable".
RichardOD
A: 

You should be alright. The point of GC.KeepAlive is just so that later in the function there is a reference to the object, and so it's never disposed. The framework isn't clever enough to know that your loop will never exit, so it never disposes the object.

Steve Cooper