0

I am developing an application that requires an initial setup phase (to be run only once) and which then executes the actual program. I did this by instantiating a class in the main file (Program.cs). This class checks if the user has already made the setup and on the basis of this it executes specific Forms or not. The problem is that once the "FormGridScheduler" form is closed with the classic X button, the program does not terminate its execution but it remains running in the background. In the form I create threads but during the "Form_Closing" event I go to abort all the threads, so there should be nothing left in execution. Anyone have any ideas on how to fix this?

This is the "Program.cs" file from which I initialize the "FormManager" class from which, subsequently, I execute the forms

static class Program {
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        //I start the form manager
        FormManager formManager = new FormManager();
    }
}

This is the FormManager class

class FormManager {
    public FormManager() {
        //I check if the user has already set up the program or not
        if (!Settings.Default.SetupDone) {
            //If you haven't done the setup yet, I start the corresponding forms
            Application.Run(new FormSetup());

            //I check if the user has closed the setup screen before completing it
            if (Settings.Default.SetupDone) {
                //I execute the main form   
                Application.Run(new FormGridScheduler());

            }
        } else {
            //I execute the main form
            Application.Run(new FormGridScheduler());

        }
    }
}

Thanks for your attention and patience. Any suggestion is welcome!

justcivah
  • 97
  • 11
  • You probably are getting an exception in the form an not getting to the close. You should have a try/catch in form with a finally to make sure form always closes. – jdweng Apr 28 '21 at 16:04
  • No, by debugging i saw that the form closes without exceptions. The debug goes through till the end of the class "FormManager", then it goes back to the "Program.cs" main and it stops there, after the new "FormManager" instance creation. – justcivah Apr 28 '21 at 16:24
  • See following : https://stackoverflow.com/questions/10206271/how-to-exit-a-windows-forms-c-program?force_isolation=true – jdweng Apr 28 '21 at 16:39
  • I found the problem. When I stop the thread, the UDP listener that is in it continues to listen, even if the thread has been closed, so the program never ends. I had to terminate the listener directly on the occurrence of the FormClosing event. Anyway thank you very much for your help and availability! – justcivah Apr 28 '21 at 19:42

0 Answers0