c# - 如何正确关闭在线程中打开的 TcpClient

标签 c# multithreading sockets tcp tcpclient

我通过 Thread 连接到 TcpClient。现在 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);
                }
            }
            ...

现在这里是关闭和重新启动线程和 TcpClient 的代码:

 _shutdownEvent.WaitOne(0);
 _thread.Abort();

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

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

最佳答案

将 _shutdownEvent 声明为 AutoResetEvent。

AutoResetEvent _shutdownEvent = new AutoResetEvent(false);

去掉Dowork方法中的外层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();

关于c# - 如何正确关闭在线程中打开的 TcpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26112888/

相关文章:

c# - XNA 中让玩家在屏幕上流畅绘画的最佳方法是什么?

c# - 如何在文本框中设置固定行距?

c# - 什么时候使用 C# 结构(值类型)会牺牲性能?

JavaFX:任务不会更新 UI

java - 检查和控制实际并行运行的应用程序线程数

c - 第一次使用 select(),可能是一个基本问题?

C#自定义数据库引擎,如何实现SQL

c++ - 锁定多个线程

.net - 如何在 TCP 客户端(套接字)上的 VB.NET 中实现 TCP KeepAlive

.NET TCPClient 连接状态