views:

23

answers:

1

I've a thread that runs following tcpConnect method. I wish to stop it at any given time by setting Program.PrepareExit to true. However my program is stuck at:
Int32 bytes = stream.Read(data, 0, data.Length); and doesn't really react to Program.PrepareExit set to true. How can i make it to always quit when I tell it so?

    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;
    }
+1  A: 

Three options suggest themselves:

  • Make the thread a daemon (background) thread. The process will exit when the only live threads are daemon threads
  • Set a timeout on the read call, possibly having to change to use the underlying socket API. That won't be pretty, to be honest.
  • Use asynchronous IO. Also a bit of a pain.

Do you need this thread to do anything in terms of an orderly shutdown? If not, the daemon thread approach would probably be simplest.

Jon Skeet
I just need this thread to be shutdown so i can close my program. Tcp connection can be dropped as long as it doesn't do it a way that will be able to crash tcp server.
MadBoy
changed it to { IsBackground = true }; and it cleanly exits :-) Thanks
MadBoy