需要调用 Application.Exit() 两次

时间:2021-03-04 20:02:31

标签: c#

我正在运行一个 winform 应用程序,它在 notifyIcon 上使用 contextMenuStrip 退出应用程序。退出函数停止另一个正在运行的线程,关闭图标可见性,然后退出应用程序。出于某种原因,尽管我必须两次调用 Application.Exit() 才能退出应用程序。我搜索了我的所有代码,但没有找到另一个 Application.Run() 调用,所以我不确定是什么导致了这种情况。

这些是正在运行的主要方法:

    private static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Thread socketThread = new Thread(ServerStream.RunServer);
        socketThread.Start();

        Application.Run(new LicenseManagerForm());
    }

    private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        ServerStream.StopListenerTask();
        NotifyIcon.Visible = false;
        Application.Exit();
        Application.Exit();
    }

    internal static async void RunServer()
    {
        // Create an IPv4 TCP/IP socket.
        TcpListener serverSocket = new TcpListener(IPAddress.Any, 11000);

        // Listen for incoming connections.
        serverSocket.Start();

        while (!_stopServer)
        {
            try
            {
                TcpClient clientRequest = await GetTcpClient(serverSocket, _cancellationTokenSource.Token);
                if (clientRequest != null) AuthenticateClient(clientRequest);
            }
            catch (Exception e)
            {
                //Program.WriteTextToStatusBar(e.ToString());
                _ = MessageBox.Show(e.ToString());
                throw;
            }
        }
    }

    private static async Task<TcpClient> GetTcpClient(TcpListener listener, CancellationToken token)
    {
        _ = token.Register(listener.Stop);

        try
        {
            return await listener.AcceptTcpClientAsync().ConfigureAwait(false);
        }
        catch (ObjectDisposedException)
        {
            if (token.IsCancellationRequested) return null;
            throw;
        }
    }

    internal static void StopListenerTask()
    {
        _stopServer = true;
        _cancellationTokenSource.Cancel();
    }

这里有什么会导致第一个 Application.Exit() 失败的吗?

0 个答案:

没有答案
相关问题