C#程序不能完全关闭的问题,后台可能还有线程之类的在运行,总之按了关闭按钮却仍在运行,请高手改一下
让程序按了关闭按钮后就能全部关闭(好像application.exit()也不好使)publicpartialclassForm1:Form{boolaSwitch=tr...
让程序按了关闭按钮后就能全部关闭(好像application.exit()也不好使)
public partial class Form1 : Form
{
bool aSwitch = true;
private StringBuilder sb = new StringBuilder();
Thread thread;
private void ReceiveData()
{
while (aSwitch)
{
UdpClient udpClient = new UdpClient(8888);
IPEndPoint remote = null;
try
{
byte[] bytes = udpClient.Receive(ref remote);
string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
sb.Append("" + DateTime.Now + ",接收自" + remote.Address.ToString() + "的消息:" + str + "\r\n");
//textBox1.Text = sb.ToString();
Action action = () => textBox1.Text = sb.ToString();
textBox1.BeginInvoke(action); //跨线程调用
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
udpClient.Close();
Thread.Sleep(20);//每20毫秒一次
}
}
public Form1()
{
InitializeComponent();
thread= new Thread(ReceiveData);
thread.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
aSwitch = false;
thread.Abort();
}
} 展开
public partial class Form1 : Form
{
bool aSwitch = true;
private StringBuilder sb = new StringBuilder();
Thread thread;
private void ReceiveData()
{
while (aSwitch)
{
UdpClient udpClient = new UdpClient(8888);
IPEndPoint remote = null;
try
{
byte[] bytes = udpClient.Receive(ref remote);
string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
sb.Append("" + DateTime.Now + ",接收自" + remote.Address.ToString() + "的消息:" + str + "\r\n");
//textBox1.Text = sb.ToString();
Action action = () => textBox1.Text = sb.ToString();
textBox1.BeginInvoke(action); //跨线程调用
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
udpClient.Close();
Thread.Sleep(20);//每20毫秒一次
}
}
public Form1()
{
InitializeComponent();
thread= new Thread(ReceiveData);
thread.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
aSwitch = false;
thread.Abort();
}
} 展开
4个回答
展开全部
为Form增加FormClosing事件,然后添加以下的几句代码,后就OK了。
比如:
private void Home_FormClosing(object sender, FormClosingEventArgs e)
{
System.Environment.Exit(System.Environment.ExitCode);
this.Dispose();
this.Close();
}
修改你的
private void Form1_FormClosing(object sender, FormClosingEventArgs e)方法就可以了
比如:
private void Home_FormClosing(object sender, FormClosingEventArgs e)
{
System.Environment.Exit(System.Environment.ExitCode);
this.Dispose();
this.Close();
}
修改你的
private void Form1_FormClosing(object sender, FormClosingEventArgs e)方法就可以了
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
在Form1()里面thread.Start();前面加上一句。
thread.IsBackground = true;
thread.IsBackground = true;
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
Environment.Exit(Environment.ExitCode)
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询