C#应用程序有时无法在关闭时退出

3
我的应用程序阻止了Windows关机,但只有在一些电脑上出现问题,而且不是每次都会发生。这个问题很难调试。 我认为这是由于我的TCP服务器引起的。它是一个异步服务器,我的应用程序处理CloseReason == WindowsShutDown。 当这种情况发生时,我的应用程序仍然作为进程运行,但无法从任务栏/系统托盘访问。
我想知道是否有人能看到我的服务器代码中有任何明显的问题。
以下是我的服务器代码。 Stop()方法从主窗体Close()事件中调用。
public class MantraServer
    {
        protected int portNumber;
        private bool ShuttingDown = false;

        //the main socket the server listens to
        Socket listener;

        //Constructor - Start a server on the given IP/port
        public MantraServer(int port, IPAddress IP)
        {
            this.portNumber = port;
            Start(IP);
        }

        /// 
        /// Description: Start the threads to listen to the port and process
        /// messages.
        ///
        public void Start(IPAddress IP)
        {
            try
            {
                //We are using TCP sockets
                listener = new Socket(AddressFamily.InterNetwork,
                                          SocketType.Stream,
                                          ProtocolType.Tcp);

                //Assign the any IP of the machine and listen on port number 3000
                IPEndPoint ipEndPoint = new IPEndPoint(IP, 3000);

                //Bind and listen on the given address
                listener.Bind(ipEndPoint);
                listener.Listen(10);

                //Accept the incoming clients
                listener.BeginAccept(new AsyncCallback(OnAccept), listener);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "MANTRA Network Start Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// Decription: Stop the threads for the port listener.
        public bool Stop()
        {
            try
            {
                ShuttingDown = true;
                listener.Shutdown(SocketShutdown.Both);
                listener.Close();
                listener = null;
                System.Threading.Thread.Sleep(500); //wait for half second while the server closes
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// 
        /// Decription: Call back method to accept new connections.
        /// <param name="ar">Status of an asynchronous operation.</param>
        private void OnAccept(IAsyncResult ar)
        {
            try
            {
                if (!ShuttingDown)
                {
                    MantraStatusMessage InMsg = new MantraStatusMessage();
                    InMsg.Socket = ((Socket)ar.AsyncState).EndAccept(ar);
                    //Start listening for more clients
                    listener.BeginAccept(new AsyncCallback(OnAccept), listener);

                    //Once the client connects then start receiving the commands from them
                    InMsg.Socket.BeginReceive(InMsg.buffer, 0, InMsg.buffer.Length, SocketFlags.None,
                        new AsyncCallback(OnReceive), InMsg);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "MANTRA Network Accept Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        ///  
        /// Receives the data, puts it in a buffer and checks if we need to receive again.  
        public void OnReceive(IAsyncResult result)
        {
            MantraStatusMessage InMsg = (MantraStatusMessage)result.AsyncState;
            int read = InMsg.Socket.EndReceive(result);
            if (read > 0)
            {
                for (int i = 0; i < read; i++)
                {
                    InMsg.TransmissionBuffer.Add(InMsg.buffer[i]);
                }
                //we need to read again if this is true  
                if (read == InMsg.buffer.Length)
                {
                    InMsg.Socket.BeginReceive(InMsg.buffer, 0, InMsg.buffer.Length, SocketFlags.None, OnReceive, InMsg);
                    Console.Out.WriteLine("Message Too big!");
                }
                else
                {
                    Done(InMsg);
                }
            }
            else
            {
                Done(InMsg);
            }
        }

        ///  
        /// Deserializes and outputs the received object  
        public void Done(MantraStatusMessage InMsg)
        {
            Console.Out.WriteLine("Received: " + InMsg.msg);
            MantraStatusMessage received = InMsg.DeSerialize();
            Console.WriteLine(received.msg.Message);
        }
    }

编辑

感谢Hogan提供了关于Close()调用的更多信息:

由于套接字未连接,并且在使用sendto调用发送数据报套接字时未提供地址,因此禁止发送或接收数据请求。

还不完全确定这意味着什么。

2个回答

1

你需要向Windows事件日志中添加一些日志记录,以了解发生了什么。

最好的起点是在返回false的catch块中(因为这会阻止Windows关闭)。如果你在那里记录原因,那么至少你可以查看事件日志,以了解为什么你的服务无法关闭。


谢谢Hogan - 看起来listener.ShutDown()调用正在生成异常。我不知道为什么会发生这种情况?在测试期间不应该发送或接收任何数据,但是这个调用仍然会像上面我的编辑一样生成错误... - Simon
你能否将抛出错误的语句包装在类似于 if (listener.connected) listener.ShutDown(); 的东西中吗? - Hogan
是的,我尝试了Disconnect()但套接字未连接。现在我正在尝试有条件的Shutdown()。看看这是否解决了我的问题。干杯 - Simon

1

编程相关内容,应注意当异步方法回调时,始终确保调用EndXXX相应的方法。以下情况下您可能未这样做:

InMsg.Socket = ((Socket)ar.AsyncState).EndAccept(ar);

因为它位于!shuttingDown块中。调用它...捕获错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接