2010-06-19 66 views
1

我有一個線程運行以下tcpConnect方法。我希望在任何時候通過將Program.PrepareExit設置爲true來停止它。但是我的程序停留在:
Int32 bytes = stream.Read(data, 0, data.Length);並且沒有真正反應Program.PrepareExit設置爲true。我怎麼能讓它總是退出,當我這樣說?如何讓TcpClient在線程中停止?

public static readonly Thread MyThreadTcpClient = new Thread(ThreadTcpClient); 
    private static void ThreadTcpClient() { 
     Connections.tcpConnect(ClientTcpIp, ClientTcpPort); 
    } 

     public static void Main() { 

      MyThreadTcpClient.Start(); 
      .... some code.... 
      Program.PrepareExit = true; 
     } 

    public static bool tcpConnect(string varClientIp, int varClientPort) { 
     var client = new TcpClient(); 
     try { 
      client = new TcpClient(varClientIp, varClientPort) {NoDelay = true}; 
      NetworkStream stream = client.GetStream(); 
      var data = new Byte[256]; 
      while (!Program.PrepareExit) { 
       Int32 bytes = stream.Read(data, 0, data.Length); 
       string varReadData = Encoding.ASCII.GetString(data, 0, bytes); 
       if (varReadData != "" && varReadData != "echo") { 
        VerificationQueue.EnqueueRelease(varReadData); 
       } 
      } 
     } catch (ArgumentNullException e) { 
      MessageBox.Show(e.ToString(), "ArgumentNullException"); 
      tcpConnect(varClientIp, varClientPort); 
     } catch (SocketException e) { 
      MessageBox.Show(e.ToString(), "SocketException"); 
      tcpConnect(varClientIp, varClientPort); 
     } catch (IOException e) { 
      if (e.ToString() != "Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.") { 
      } 
      MessageBox.Show(e.ToString()); 
      tcpConnect(varClientIp, varClientPort); 
     } finally { 
      client.Close(); 
     } 
     return false; 
    } 

回答

2

三個選項暗示自己:

  • 使線程守護進程(背景)線程。當只有活動線程爲守護進程線程時,進程將退出
  • 在讀取調用上設置超時,可能必須更改爲使用底層套接字API。說實話,這不會很漂亮。
  • 使用異步IO。也有點痛苦。

你需要這個線程做什麼什麼在有序關機方面?如果沒有,守護線程方法可能是最簡單的。

+0

我只是需要這個線程被關閉,所以我可以關閉我的程序。只要不這樣做就可以使tcp服務器崩潰。 – MadBoy 2010-06-19 22:33:53

+2

將其更改爲{IsBackground = true};它乾淨地退出:-)謝謝 – MadBoy 2010-06-19 22:40:56