在Visual Studio 2017上,如何在try / catch中关闭软件?

时间:2019-01-21 23:13:08

标签: c# winforms

我正在Visual Studio 2017上用C#开发一个软件,并且我希望它在数据库关闭时不初始化,因此我尝试了下面的try / catch,但仍然无法退出该软件,我有两个按钮退出,它们起作用,但是try-catch上的退出不起作用。我已经尝试了很多事情,将app.exit并关闭代码放在许多不同的地方,从其他函数调用,这是行不通的。 这是代码:

public partial class Form1 : Form
{
    int errobd = 0;
    public Form1()
    {
        InitializeComponent();
        try
        {
            string connectionString = "server=localhost;user id=root;persistsecurityinfo=True;database=bd_cem";
            MySqlConnection connection = new MySqlConnection(connectionString);
            connection.Open();
            connection.Close();
        }
        catch
        {
            Close();

            // at this point, the errobd++ works, so the if down there will be true
            errobd++;
            MessageBox.Show("Error message.");
            Application.Exit();
            Debug.WriteLine("ERRO = " + errobd);
        }
        if(errobd>0)
        {
            Sairsembanco();
        }

        LoadSalaNome();
        LoadADI();
    }

并且经过所有这些努力,LoadSalaNome()函数仍然尝试运行,由于数据库已关闭而使软件崩溃。

2 个答案:

答案 0 :(得分:2)

您也可以尝试以下方法:

Environment.Exit(exitCode)

这将终止进程,并为底层操作系统提供指定的退出代码。这要求您具有SecurityPermissionFlag.UnmanagedCode权限,否则会发生SecurityException错误。 如果正在运行控制台应用程序,则可以使用此调用。

答案 1 :(得分:0)

Application.Exit不一定导致应用程序关闭-它“停止所有线程上所有正在运行的消息循环并关闭应用程序的所有窗口”。在这里,您的应用程序将在catch子句之后继续运行。

要退出,请使用Environment.Exit(如果您使用的是主方法,请使用return)。