bool closing = false;
bool listening = false;
//打开or关闭串口
btnOpen_Click()
{
if(btnOpen.Text == "Open")
{
serial.Open();
}
else
{
closing = true;
while(listening)Application.DoEvents();
serial.Close();
closing = false;
}
}
//串口数据监听
serial_DataReceived()
{
if(closing)return;
try
{
listening = true;
//读取数据等相关操作
……
}
catch{}
finally{listening=false;}
}
//退出程序
btnExit_Click()
{
closing = true;
while(listening)Application.DoEvents();
serial.Close();
Application.Exit();
}