我用TcpClient连接到Thread。现在TcpClient的连接在线程中已正确打开,但TcpClient的关闭和线程未正确执行。我不知道为什么。
下面是我要开始的线索:

 private System.Threading.Thread _thread;
 private ManualResetEvent _shutdownEvent = new ManualResetEvent(false);

_thread = new Thread(DoWork);
_thread.Start();

下面是TcpClient连接:
private void DoWork()
{
while (!_shutdownEvent.WaitOne(0))
{
    try
    {
        client = new TcpClient();
        client.Connect(new IPEndPoint(IPAddress.Parse(ip),intport));
        //Say thread to sleep for 1 secs.
        Thread.Sleep(1000);
    }
    catch (Exception ex)
    {
        // Log the error here.
        client.Close();
        continue;
    }
    try
    {
        using (stream = client.GetStream())
        {

           byte[] notify = Encoding.ASCII.GetBytes("Hello");
           stream.Write(notify, 0, notify.Length);

            byte[] data = new byte[1024];
            while (!_shutdownEvent.WaitOne(0))
            {
                int numBytesRead = stream.Read(data, 0, data.Length);
                if (numBytesRead > 0)
                {
                    line= Encoding.ASCII.GetString(data, 0, numBytesRead);
                }
            }
            ...

下面是关闭和重新启动线程并执行以下操作的代码:
 _shutdownEvent.WaitOne(0);
 _thread.Abort();

 //Start Again
 _thread = new Thread(DoWork);
 _thread.Start();

请帮助我停止和启动线程并正确TcpClient
谢谢。

最佳答案

将关闭事件声明为自动重置事件。

AutoResetEvent _shutdownEvent = new AutoResetEvent(false);

用销子法去掉外侧的while环
private void DoWork()
    {
        try
        {
            client = new TcpClient();
            client.Connect(new IPEndPoint(IPAddress.Parse(ip), intport));
            //Say thread to sleep for 1 secs.
            Thread.Sleep(1000);
        }
        catch (Exception ex)
        {
            // Log the error here.
            client.Close();
            return;
        }
        try
        {
            using (stream = client.GetStream())
            {
                byte[] notify = Encoding.ASCII.GetBytes("Hello");
                stream.Write(notify, 0, notify.Length);

                byte[] data = new byte[1024];
                while (!_shutdownEvent.WaitOne(0))
                {
                    int numBytesRead = stream.Read(data, 0, data.Length);
                    if (numBytesRead > 0)
                    {
                        line = Encoding.ASCII.GetString(data, 0, numBytesRead);
                    }
                }
            }
        }
        catch
        {
        }
        finally
        {
            if (stream != null)
                stream.Close();
            if (client != null)
                client.Close();
        }
    }

使用_shutdownEvent.Set()表示事件。
_shutdownEvent.Set(); //Set, not Wait
//_thread.Abort(); //and you don't have to abort the thread since it will end gracefully after it break out of the while loop
while (_thread.IsAlive) ; //wait until the first thread exit

//Start Again
_thread = new Thread(DoWork);
_thread.Start();

10-04 22:01
查看更多