停止线程

时间:2010-11-09 08:25:10

标签: c# winforms

我有一个winform应用程序,其中包含form1和program.cs文件。在program.cs我初始化form1,除此之外,我有一个服务器包括在内。我的问题是:当我关闭表单时如何停止线程?这是我的program.cs文件的一部分:

public void start()
        {
            this.tcpListener = new TcpListener(IPAddress.Any, 3000);
            this.listenThread = new Thread(new ThreadStart(ListenForClients));
            this.listenThread.Start();
        }


        private void ListenForClients()
        {
            //MessageBox.Show("in thread");
            this.tcpListener.Start();

            while (true)
            {
                //blocks until a client has connected to the server
                TcpClient client = this.tcpListener.AcceptTcpClient();

                //create a thread to handle communication 
                //with connected client
                sThread a = new sThread(form1, listaThreads);
                listaThreads.Add(a);
                Thread clientThread = new Thread(new ParameterizedThreadStart(a.HandleClientComm));
                clientThread.Start(client);
            }
        }

3 个答案:

答案 0 :(得分:3)

而不是主动中止它们,你应该告诉他们应该停止并允许他们在自己的时间停止。如果您使用的是BackgroundWorker,则可以使用CancelAsync方法。对于像您的示例中手动创建的线程,您可以使用线程必须偶尔检查的布尔标志(具有适当的同步)。当您的程序即将关闭时设置标志。避免在线程中调用阻塞方法 - 使用异步方法,例如BeginAcceptTcpClient而不是AcceptTcpClient

如果您正在使用(或可以升级到).NET 4,那么您还应该考虑使用任务Task Parallel Librarycancellable

答案 1 :(得分:3)

您可以从其他主题调用Close()的{​​{1}}。

TcpListener只会调用TcpListener.Close(),这是线程安全的。

我不确定Socket.Close()是如何反应的,但你必须检查一下。至少它会以正常方式停止你的听力线程。

所以,你这样做:

AcceptTcpClient

这将很好地关闭你的线程。

答案 2 :(得分:0)

在运行异步的方法中,你应该检查一个布尔标志,说cancel当你想要停止线程时从外面设置为true。

public bool cancel = false;

public void MethodRuningOnThread()
{
   while(!cancel)
   {
      //do stuff
   }
}

建议不要使用Thread.Abort()方法。