2016-09-14 93 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對這個問題的迴應,他提到永遠不會開始一個你無法禮貌地停下來的線索。