5

I have a custom ApplicationContext and I'm trying to terminate it if specific conditions are met. I am using a Mutex to ensure a single instance.

I've tried base.OnMainFormClosed(null, null);. Application.Exit() and ExitThread. Everything stops processing, but the process itself is still running.

Complete Main() method:

static void Main()
    {
        bool firstInstance;
        using (Mutex mutex = new Mutex(true,
                                   @"Global\MyApplication",
                                   out firstInstance))
        {
            if (!firstInstance)
            {
                MessageBox.Show("Another instance is already running.");
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

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

What's the correct technique?

mattdwen
  • 5,288
  • 10
  • 47
  • 61

3 Answers3

11
   Application.Run(new CustomContext());

That's okay, but you don't store a reference to the CustomContext object you created. There's thus no way to call its ExitThread method. Tweak it like this:

class Program {
    private static CustomContext appContext;

    [STAThread]
    public static void Main() {
       // Init code
       //...
       appContext = new CustomContext();
       Application.Run(appContext);
    }
    public static void Quit() {
        appContext.ExitThread();
    }
}

Now you can simply call Program.Quit() to stop the message loop.

Check my answer in this thread for a better way to implement a single-instance app. The WindowsFormsApplicationBase class also offers the ShutdownStyle property, probably useful to you instead of ApplicationContext.

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
0

Calling Application.Exit stops your program's message loop.
This causes the main Application.Run call (typically in Main()) to terminate.

After calling Applcication.Exit(), any code in Main() after the Application.Run() call will execute.

Application.Run is typically the last line in Main(), so calling Applcication.Exit() will usually cause the process to stop.

You probably have more code after Application.Run(), or a deadlock somewhere in disposal.


Pause the process in a debugger and check what it's doing.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • The debugger pauses on the `Application.Run` line. The call stack is showing `[External Code]` above and below. I am also using a mutex to ensure a single instance, which I probably should have pointed out at the start. I'll update the question with the complete method. – mattdwen Aug 04 '10 at 09:22
-2

You can just call in thread that you want to exit

Thread.CurrentThread.Abort();
Ivan Leonenko
  • 2,363
  • 2
  • 27
  • 37