1

我的双重角色应用程序(在另一台机器上运行的“服务器”角色)在我关闭它时实际上无法关闭(关闭应用程序后它仍在任务管理器的“进程”列表中)。

我不知道它是否因为它的 TcpListener 类仍在侦听而保持“活动”,或者 TcpListener 类是否仍在侦听,因为应用程序还没有真正关闭。

所以,我添加了两段代码:

1)这里的最后一行(listener.Stop()):

static void Server()     
{
    TcpListener listener = new TcpListener(IPAddress.Any, 51111);
    listener.Start();
    var shouldExit = false;
    while (!shouldExit)
        using (TcpClient c = listener.AcceptTcpClient())
        {
            using (NetworkStream n = c.GetStream())
            {
                string msg = new BinaryReader(n).ReadString();
                if (msg == "exit")
                    // Client told us to exit... 
                    shouldExit = true;
                BinaryWriter w = new BinaryWriter(n);
                w.Write(msg + " back atcha!");
                w.Flush(); // Must call Flush because we're not disposing the writer. 
            }
        }
    //listener.EndAcceptTcpClient; //unnecessary because AcceptTcpClient() is wrapped in a "using"?
    listener.Stop();
}

...和:

2)

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Close(); // The app/process is staying "live" even after shutting down the app...maybe this will help?
        }
// but on closing the app, I got: "System.StackOverflowException was unhandled" here...?

为什么调用 Close 时会出现 Stack 溢出?

4

0 回答 0