简体   繁体   English

如何用无限循环实现单例模式 - C#

[英]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. 我目前正在使用C#中的应用程序,该应用程序在其他方法调用的每次迭代之后使用Thread.Sleep调用在无限循环上运行。 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. 我已经在方法的末尾插入了KeepAlive调用,以确保单个互斥锁按预期工作,如各种网站所述。 The call to KeepAlive is supposed to keep garbage collection from throwing away the mutex, since .NET looks forward to anticipate/optimize garbage collection. 对KeepAlive的调用应该可以防止垃圾收集丢弃互斥锁,因为.NET期待预期/优化垃圾收集。

My question is, since the actual call to KeepAlive never gets reached, should I put it in the loop after Thread.Sleep? 我的问题是,由于实际上对KeepAlive的调用永远不会到达,我应该在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. 编译器警告KeepAlive永远不会被调用,我担心它会在我的垃圾收集防止算法中忽略这一行。

Mutex is disposable. Mutex是一次性的。 Why not wrap it in a using ? 为什么不把它包装成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. 请注意,这甚至不会将新Mutex分配给命名变量。

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. GC.KeepAlive的重点只是在函数的后面有一个对象的引用,因此它永远不会被释放。 The framework isn't clever enough to know that your loop will never exit, so it never disposes the object. 该框架不够聪明,无法知道您的循环永远不会退出,因此它永远不会丢弃该对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM