本文介绍了当主应用程序关闭时,线程不会终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我试图构建一个使用tcp套接字交换文件的应用程序,我使用了一个线程来列出端口,该应用程序似乎运行良好,但是当我关闭服务器时,该应用程序或该线程挂在了内存中.请帮我解决这个问题..

Hi,

I trying to build an application to exchange files using tcp sockets, I have used a thread to have port listing, the app seems to work fine except that when I close the server the app or the thread hang in memory. please help me to solve this problem..

public void threadHandler()
        {
            Socket handlersocket = (Socket)alSockets[alSockets.Count - 1];
            NetworkStream networkStream = new NetworkStream(handlersocket);
            int thisRead = 0;
            int blockSize = 1024;
            byte[] dataByte = new byte[blockSize];
            lock (this)
            {
                // Only one process can access
                // the same file at any given time
                Stream fileStream = File.OpenWrite(@"c:\upload");
                while (true)
                {
                    thisRead = networkStream.Read(dataByte, 0, blockSize);

                    fileStream.Write(dataByte, 0, thisRead);
                    if (thisRead == 0) break;
                }
                fileStream.Close();
                networkStream.Close();
            }
            lBConnections.Items.Add("File Recieved");
            handlersocket = null;
        }
        public void ThreadListener()
        {

                TcpListener tcpListener = new TcpListener(8880);
                tcpListener.Start();
                while (true)
                {
                    Socket handlerSocket = tcpListener.AcceptSocket();
                    if (handlerSocket.Connected)
                    {

                        lBConnections.Items.Add(handlerSocket.RemoteEndPoint.ToString() + "..Connected.");

                        lock (this)
                        {
                            alSockets.Add(handlerSocket);
                        }
                        ThreadStart thdstHandler = new ThreadStart(threadHandler);
                     Thread    thdHandler = new Thread(thdstHandler);

                        thdHandler.Start();

                    }

                }
        }

        private void ReceiveFile_Load(object sender, EventArgs e)
        {
            this.CenterToScreen();
            IPHostEntry IPHost = Dns.GetHostByName(Dns.GetHostName());
            lBConnections.Text = "Host IP address is " +
            IPHost.AddressList[0].ToString();
            alSockets = new ArrayList();

          Thread   thdListener = new Thread(new ThreadStart(ThreadListener));
            thdListener.Start();
        }

推荐答案

thdListener.IsBackground = true;


主应用程序结束后,该线程将停止.


The thread will stop after the main application ends.



thread.abort();


这篇关于当主应用程序关闭时,线程不会终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:48
查看更多