2016-09-14 37 views
3

我有一个程序,启动一个服务器线程,该线程我等待用户的连接,但有时(如果用户按下“E”)我想关闭该服务器线程,但它不工作。我试图杀多线程服务器的线程C#

'thread'.abort() - but it's freezing and not stopping the thread 

这里的服务器代码:

private void start() 
    { 
     try 
     { 
      this.serverSocket = new TcpListener(8888);      // creating the Server TCP socket 
      this.clientSocket = default(TcpClient);       // creating the User socket variable 

      // starting the server 
      this.serverSocket.Start(); 

      Console.WriteLine("->> server started");      // printing to log 

      // for always 
      while (true) 
      { 
       counter += 1;            // new user 
       this.clientSocket = this.serverSocket.AcceptTcpClient(); // accepting user 
       Console.WriteLine(" ->> User connected");     // printing to log 
       // User creatinon 
       ConnectedUser user = new ConnectedUser(this.clientSocket); 
       user.startListerner(); 
      } 

      this.clientSocket.Close(); 
      this.serverSocket.Stop(); 
      Console.WriteLine(" >> " + "exit"); 
      Console.ReadLine(); 
     } 
     catch 
     { 
      Console.WriteLine("Error launching the Server"); 
     } 

    } 

,我跑这样说:

this.server = new Thread(start); 
server.Start(); 

我想终止它,我该怎么办呢?

+0

http://stackoverflow.com/questions/2251964/c-sharp-thread-termination-and-thread-abort – xxbbcc

回答

2

你必须使用一个CancellationTokenSource信号你的线程终止本身。不推荐使用Thread.Abort,因为它会在不先让它正确清理的情况下终止线程。

要使用取消标记,您创建的CancellationTokenSource一个实例,然后传递令牌到你的线程函数(或者说包装了新线程状态的对象。里面的线程函数就可以检查的的IsCancellationRequested财产您可以将相同的取消令牌传递给I/O功能,以尝试取消阻止操作。

有关由Thread.Abort引起的可能问题的更多详细信息,请参阅this question/ answers。阅读Eric Lippert对这个问题的回应,他提到永远不会开始一个你无法礼貌地停下来的线索。