public partial class MainWin : Form
    {
private Thread rmt = null;
pbulic ListenerDone = false;
public void startReciveMsg()
        {
            ListenerDone = false;
            try
            {
                rmt = new Thread(new ThreadStart(StartListener));
                rmt.IsBackground = true;
                rmt.Start();
            }
            catch
            {            }
        }        public void stopReciveMsg()
        {
            ListenerDone = true;
            try
            {
                if (rmt != null)
                {
                    rmt.Abort();
                    //rmt.Join();//如果不取消这句   UI  一只 假死 ,  也不 出现 未响应....   
//但是 要是 取消了  就会出先  再调用 startReciveMsg()这个 的时候  程序 自动 关闭......      
//  请教 扎会事????
                    rmt = null;
                }
            }
            catch
            {
                rmt = null;
            }
        }public void StartListener()
        {
            UdpClient listener = new UdpClient(listenPort);
            //任意IP,设端口为0表示任意
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
            try
            {
                while (!ListenerDone)
                {
                    byte[] bytes = listener.Receive(ref groupEP);
                    string strIP = groupEP.Address.ToString();
                    string strInfo = Encoding.GetEncoding("gb2312").GetString(bytes, 0, bytes.Length);
                    if (strInfo != "" && strInfo != null)
                    {
                        ListenerCallBack(strIP, strInfo);
                    }
                    if (ListenerDone) break;
                    Thread.Sleep(1000);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                listener.Close();
            }
        }
}

解决方案 »

  1.   

    如果不取消这句  UI  一只 假死 ,  也不 出现 未响应
    --------------------------------
    当然,因为你的 while (!ListenerDone) 条件一直为TRUE,一直执行接收数据,但是 要是 取消了  就会出先  再调用 startReciveMsg()这个 的时候  程序 自动 关闭...... 
    -------------------------------
    我也不是很清楚,是没有释放,还是线程已经被终结了,无法响应,请楼下的指正。
      

  2.   

    listener.Receive(ref groupEP); 
    这里 会阻塞住线程的,知道收到信息,当线程被其他线程阻塞住的时候,是很难终止的,然后你还去做join,当然就是死循环了。