How to implement a singleton pattern with an infinite loop - C#
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.
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.
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.
精彩评论