相关疑难解决方法(0)

GC.KeepAlive与使用

在他关于防止应用程序的多个实例文章中,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!
}
Run Code Online (Sandbox Code Playgroud)

他解释说,GC.KeepAlive(m)是防止垃圾收集器尽早收集互斥锁所必需的,因为没有额外的引用.

我的问题:将mutex包装在一个使用中做同样的事情?也就是说,以下是否也会阻止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 …
Run Code Online (Sandbox Code Playgroud)

c# garbage-collection keep-alive

14
推荐指数
2
解决办法
6299
查看次数

标签 统计

c# ×1

garbage-collection ×1

keep-alive ×1