非正常退出,如何改呢?
如下的程序,用于侦听设备发来的信号。
侦听程序运行中如果设备中途关闭后重新打开,程序有时会自行退出。如何处理这个情况呢?
多次测试,只有少数出现上述情况。
//开始监听
private void button1_Click(object sender, EventArgs e)
{
try
{
myIP = IPAddress.Parse(textBox1.Text);
}
catch { MessageBox.Show("您输入的IP地址格式不正确,请重新输入!"); }
try
{
Thread thread = new Thread (new ThreadStart(accp));
//thread.IsBackground = true;
thread.Start();
}
catch(Exception ee) {textBox2.AppendText(ee.Message);}
}
//线程同步方法 accp的代码。
private void accp()
{
MyServer = new IPEndPoint(myIP, 2300);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(MyServer);
sock.Listen(50);
while(true)
{
accSock = sock.Accept();
if (accSock.Connected)
{
Thread thread = new Thread(new ThreadStart(round));
thread.Start();
}
}
}
private void round()
{
while (true)
{
NetworkStream netStream = new NetworkStream(accSock);
netStream.Read(RecByte, 0, RecByte.Length);
DoSomthing();
}
}
// 停止监听
private void button3_Click(object sender, EventArgs e)
{
try
{
sock.Close();
accSock.Close();
}
catch { MessageBox.Show("监听尚未开始,关闭无效!"); }
}
------解决方案--------------------
accp中侦听的地方也需要try...catch。