views:

29

answers:

1

So this tells me that I should put a GC.KeepAlive at the end of my code to keep my mutex open (to prevent multiple instances of my app happening due to early GC disposal of my mutex). But should I put the KeepAlive in my finally block or at the end of my try block?

+4  A: 

I personally would not use that approach.

The issue is that you need to have something use the mutex after your Application code (in this case, the form) completes, or it will be a candidate for GC post-optimizations.

Since Mutex implements IDisposable, you can just as easily do this:

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

        Application.Run(new Form1());
    }
}

This will work just as well, since the finally created by the using statement will prevent the mutex from being a GC candidate. I, personally, find this less confusing and cleaner code.

That being said, if you want to follow the approach from that link, just putting KeepAlive anywhere will cause the mutex to not get collected, and prevent the issue. You can put it inside your try or finally block - as long as it's after the main application code "completes". You can also ignore this and just explicitly Dispose() the mutex - as long as you use the mutex some way, it will be fine.

Reed Copsey