2010-06-19 108 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