c# - GC.KeepAlive 与使用

标签 c# garbage-collection keep-alive

在他的article about preventing multiple instances Michael Covington 展示了一个应用程序的代码:

static void Main()                  // args are OK here, of course
{
    bool ok;
    m = new System.Threading.Mutex(true, "YourNameHere", out ok);

    if (! ok)
    {
        MessageBox.Show("Another instance is already running.");
        return;
    }

    Application.Run(new Form1());   // or whatever was there

    GC.KeepAlive(m);                // important!
}

他解释说,需要 GC.KeepAlive(m) 来防止垃圾收集器提前收集互斥体,因为没有对它的额外引用。

我的问题:将互斥量包装在 using 中会做同样的事情吗?也就是说,以下是否也会阻止 GC 从我身下拉出地毯?

static void Main()                  // args are OK here, of course
{
    bool ok;
    using (var m = new System.Threading.Mutex(true, "YourNameHere", out ok))
    {
        if (! ok)
        {
            MessageBox.Show("Another instance is already running.");
            return;
        }

        Application.Run(new Form1());   // or whatever was there
    }
}

我的直觉 react 是 using 会起作用,因为 using (应该)等同于:

Mutex m = new System.Threading.Mutex(true, "YourNameHere", out ok);
try
{
    // do stuff here
}
finally
{
    m.Close();
}

而且我认为 m.Close() 足以向 JIT 编译器发出另一个引用的信号,从而防止过早的垃圾收集。

最佳答案

将互斥量包装在 using 语句中确实会防止它被垃圾收集,但也会处理它(它调用 Dispose , 而不是 Close) 最后(而 GC.KeepAlive 显然不会)。

如果方法的结束真的是过程的结束,我认为它不会对您使用的任何实际差异产生影响 - 我更喜欢 using 语句处理任何实现 IDisposable 的一般原则。

如果在进程退出时互斥量没有被释放,我怀疑它的终结器会处理它 - 只要其他终结器不占用终结线程超过其超时时间。

如果终结器不处理它,我不知道 Windows 本身是否会注意到该进程不可能再拥有互斥量,因为它(进程)不再存在.我怀疑它会,但您必须查看详细的 Win32 文档才能确定。

关于c# - GC.KeepAlive 与使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/635640/

相关文章:

java - Android 内部类由于 this$0 变量而未被垃圾回收

macos - 没有网络连接时启动 NetworkState

windows-server-2008 - 如何在 Windows Server 2008 上设置 Keepalive

php - 如何在 PHP 中为多个 get 请求保持 mysql 连接打开?

javascript - Highchart 值序列映射

c# - 我需要帮助翻译这部分 ECMAScript 语法吗?

c# - 垃圾收集器是否会删除导出到 C# 的 C++ 类?

c# - 在这种情况下我真的应该实现 IDisposable 吗?

c# - 我在请求 https url 时收到错误远程服务器未找到

c# - 隐藏ZedGraph控件的灰色边框