0

I have a Winforms app that does not shut down when we close the main form. I.e. the process stays in Windows TaskManager. Here is the main program:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new ServerSimulator());
    }
}

The main form has this code in its InitializeComponent:

this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.ServerSimulatorFormClosed);

And in the ServerSimulatorFormClosed code there is:

    private void ServerSimulatorFormClosed(object sender, FormClosedEventArgs e)
    {
        if (ThornhillServerSimulator != null)
            ThornhillServerSimulator.StopListening();
        if (RamqSimulator != null)
            RamqSimulator.StopListening();
        if (SaaqSimulator != null)
            SaaqSimulator.StopListening();
        if (DisSimulator != null)
            DisSimulator.StopListening();
        if (PharmaSpaceSimulator != null)
            PharmaSpaceSimulator.StopListening();
        if (DispenserSimulator != null)
            DispenserSimulator.StopListening();
        if (AlbertaBlueCrossServerSimulator != null)
            AlbertaBlueCrossServerSimulator.StopListening();
    }

Since the main form opens with Application.Run, I assume I need to call Application.Exit to close down the appliction. But where do I put it. This app has threads as well. Could it be that they are preventing the app from closing. If yes, how do I properly shut down the app?

Ray
  • 4,679
  • 10
  • 46
  • 92
  • Similar question http://stackoverflow.com/questions/12977924/how-to-properly-exit-a-c-sharp-application – Sybren Dec 04 '14 at 19:06
  • Well, which of those methods in 'ServerSimulatorFormClosed' is getting stuck? Also, what happens if you comment out the entire set of calls? – Martin James Dec 04 '14 at 19:22
  • Are those threads ended when calling `StopListening()`? If they don't terminate, that's what's keeping your process open. – Jcl Dec 04 '14 at 20:09

1 Answers1

1

Try moving the StopListening calls from the Closed event to the Closing event.

xpda
  • 15,585
  • 8
  • 51
  • 82