我创建了从串口读取的应用程序,它工作得很好。但是当我关闭应用程序并再次运行它时会出现问题。突然从串口读取停止工作。我必须断开连接并连接USB才能修复它。
这是我的代码:
namespace Serial
{
public partial class Main : Form
{
SerialPort mainSerialPort = new SerialPort();
public Main()
{
InitializeComponent();
}
delegate void SetTextCallback(string text);
private void buttonOpen_Click(object sender, EventArgs e)
{
mainSerialPort.PortName = "COM" + numericPort.Value.ToString();
mainSerialPort.BaudRate = 115200;
mainSerialPort.Parity = Parity.None;
mainSerialPort.StopBits = StopBits.One;
mainSerialPort.DataBits = 8;
mainSerialPort.Handshake = Handshake.None;
mainSerialPort.DataReceived += DataReceived_Read;
try{
mainSerialPort.Open();
}catch (Exception ex){
labelStatus.Text = ex.GetType().ToString();
}
if (mainSerialPort.IsOpen == true){
numericPort.BackColor = Color.Green;
labelStatus.Text = "Port je otevřen!";
}else{
numericPort.BackColor = Color.Red;
}
}
private void DataReceived_Read(object sender, SerialDataReceivedEventArgs e)
{
SerialPort mySerial = (SerialPort)sender;
if (this.InvokeRequired){
listBoxRead.Invoke(new MethodInvoker(delegate {
listBoxRead.Items.Add(mySerial.ReadExisting());
listBoxRead.SelectedIndex = listBoxRead.Items.Count - 1;
}));
}
}
private void Main_FormClosed(object sender, FormClosedEventArgs e)
{
mainSerialPort.DataReceived -= DataReceived_Read;
mainSerialPort.Close();
}
}
}
答案 0 :(得分:0)
USB和串行端口是非托管资源。你必须处理它! FormClosed上的一个简单的“已关闭”将不会这样做。
答案 1 :(得分:0)
我认为这与一些未正确释放的资源有关。尝试调用Dispose方法
mainSerialPort.Close();
mainSerialPort.Dispose();