在main_FormClosed方法中,可以使用listener.Stop()方法来关闭监听线程。修改代码如下:

// 窗口关闭时关闭连接和线程
private void main_FormClosed(object sender, FormClosedEventArgs e)
{
    try
    {
        if (client != null && client.Connected)
        {
            client.Close();
        }

        if (listener != null)
        {
            listener.Stop();
        }

        if (receiveThread != null && receiveThread.IsAlive)
        {
            receiveThread.Abort();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

这样在窗口关闭时,会先关闭client和listener,然后再终止receiveThread线程

using System;using SystemCollectionsGeneric;using SystemComponentModel;using SystemData;using SystemDrawing;using SystemLinq;using SystemText;using SystemWindowsForms;using SystemNetSockets;using Syst

原文地址: https://www.cveoy.top/t/topic/iyHg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录