简体   繁体   中英

c# windows forms application leaves process running after errors

I'm writing my first c# windows forms app, and I'm new programming (I've done excel macros and years ago I used to write embedded stuff but I'm only a helpdesk drone trying to do something to help with my foreign-language study) and I'm essentially flailing about with no idea what I'm doing and googling a lot, which usually works, but I've been stuck on this all day.

My app accesses a database, and so long as it's up, everything's fine. I have try/catch/finally for the database access, and when there's an error, it's displaying the details, then closing the application - except it's still there as a background process in Task Manager and I can't figure out what it's failing to kill.

The main.cs has

static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        StartupScreen MainScreen = new StartupScreen();
        MainScreen.Show();

        Application.Run();
        Application.Exit();
    }

and the catch for the error is

catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error 7");
            if (conn2 != null)
            {
                conn2.Close();
            }
            this.Close();
            Application.Exit();
        }

If there's no errors, it exits cleanly when the user clicks the exit button or the X, but having to quit it with task manager if the database is having a hissy-fit isn't ideal. I haven't intentionally started any background processes, and Visual Studio put STAThread on the main.cs, which I'm guessing means that it's a single-thread app, but I only started trying to do this a couple of weeks ago, and my poor little humanities-student brain cannot cope.

Is try/catch the wrong way to do this in a WinForm? The beginners guide I started from was about console apps, and that's how it said to do it there, but my base assumption with all of this is that I'm missing something obvious to anyone competent...

Your Main is a little odd. The standard one is more like:

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new StartupScreen());
    }

You don't need to call Application.Exit() , either in Main or in your catch .

In the catch , calling this.Close() will close the form, causing your Application.Run to complete, and that's the end of your Main , so the app will exit.

Also, are you running your program from Visual Studio? If the process in the task manager is called yourapplication.vshost.exe , then don't worry about it - it's used by Visual Studio to help with debugging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM