开发者

C# Application not exiting on Shutdown (sometimes)

My application prevents windows shutting down, but only on some computers, and not all the time. Its a little tricky to debug. I think its due to my TCP server. It is an asynchronous server, and my application handles the CloseReason == WindowsShutDown. When this occurs, my application is still running as a process, but is not accessible from taskbar/system tray.

I was wondering if anyone can see any obvious issues with my server code.

Below is the code for my server. The Stop() method is called from the main forms Close() event.

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 开发者_StackOverflow社区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);
        }
    }

EDIT

Thanks to Hogan, some more information on the call to Close():

A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.

Not entirely sure what this means yet.


You have to add some logging to the windows event log to see what is going on.

The best place to start is in the catch that returns false (since this will stop windows from shutting down.) If you log the reason there then at least you can look at the event log to see why your service won't shut down.


You should always ensure that you call the EndXXX counterpart method for any async method when the callback occurs. You fail to do this for:

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

because it lives in a !shuttingDown block. Call it... catch the error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜