c# 退出应用时进程不关闭问题

xiaoxiao2021-02-28  70

摘要问题描述原理介绍代码实例

摘要/问题描述

在写上位机过程中需要写一个UDP持续监听的功能,实现方式选择新建while循环进程的方法。但是调试过程中发现,关闭界面后,线程还在后台持续运行。经查询资料,最终选择Thread的IsBackground属性来实现应用退出时自动结束线程。

原理介绍

线程开启后默认为前台线程,如果关闭应用,此线程不会关闭,会在系统持续运行直到此线程运行结束(本例中需要持续监听,所以线程开启了while(true)无限循环,如果主应用不abort,线程自己不会结束)。设置IsBackground属性为true后,关闭应用,此线程自动终止。

代码实例

由于项目很大,在此只贴出能够展现此博文表述问题的代码块。

// This constructor arbitrarily assigns the local port number. UdpClient udpClient = null; Thread thread; private void BUTTudpConnect_Click(object sender, EventArgs e) { if (BUTTudpConnect.Text == "connect") { udpClient = new UdpClient(Convert.ToInt32(TBLocalPort.Text)); try { udpClient.Connect(TBRemoteIP.Text, Convert.ToInt32(TBRemotePort.Text)); UdpSend( udpClient); thread = new Thread(UdpListing); thread.Start(udpClient); thread.IsBackground = true; } catch (Exception ex) { MessageBox.Show(ex.ToString()); } BUTTudpConnect.Text = "disconnect"; } else { thread.Abort(); BUTTudpConnect.Text = "connect"; udpClient.Close(); } } private void UdpListing(Object obj) { UdpClient udpClient; udpClient = (UdpClient)obj; //IPEndPoint object will allow us to read datagrams sent from any source. IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); while(true) { // Blocks until a message returns on this socket from a remote host. Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); string returnData = Encoding.ASCII.GetString(receiveBytes); // Uses the IPEndPoint object to determine which of these two hosts responded. MessageBox.Show("This is the message you received " + returnData.ToString()); } }
转载请注明原文地址: https://www.6miu.com/read-21506.html

最新回复(0)