【发布时间】:2016-06-18 21:41:30
【问题描述】:
我编写了一个从 RS-232 端口读取权重值的 C# Windows 窗体程序。
这是我的程序:
try { Brate = Convert.ToInt32(MyParam._BOUD1); }
catch { Brate = 9600; }
port = new SerialPort(MyParam._COM1, Brate, Parity.None, 8, StopBits.One);
port.DtrEnable = true;
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
if (port.IsOpen == false)
{
try
{
port.Open();
port.DiscardOutBuffer();
}
catch (Exception oex)
{
MessageBox.Show(oex.ToString());
}
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
this.Invoke(new EventHandler(DoUpdate));
}
catch (Exception ex)
{
}
}
private void DoUpdate(object s, EventArgs e)
{
try
{
lblMSG2.Text = port.ReadLine().ToString();
port.DiscardInBuffer();
}
catch (Exception ex)
{
lblMSG2.Text = ex.ToString();
}
}
这个程序运行良好,除了我尝试关闭表单以打开另一个表单。
这是我关闭串口的方法:
if (port.IsOpen == true)
{
port.DataReceived -= new SerialDataReceivedEventHandler(port_DataReceived);
try
{
port.Close();
port.DiscardOutBuffer();
}
catch (Exception oex)
{
MessageBox.Show(oex.ToString());
}
}
我的程序挂起,除了退出程序并重新启动之外,我什么也做不了。
我做错了什么?
编辑
我尝试了这里建议的所有内容
if (port.IsOpen == true)
{
//port.DataReceived -= new SerialDataReceivedEventHandler(port_DataReceived);
try
{
//port.Dispose();
// port.DiscardOutBuffer();
// port = null;
port.Close();
}
catch (Exception oex)
{
MessageBox.Show(oex.ToString());
}
}
但程序仍然挂起,除了退出程序并重新启动之外,我什么也做不了。
卡在这一行:port.Close();
【问题讨论】:
-
你的代码冻结在哪一行?
-
我不知道这个具体的类,但也许你应该在 Close() 之前调用 DiscardOutBuffer()?
-
关闭可能会锁定端口。我会尝试 port = null;
-
感谢您的帮助,我已经更新了问题
-
嘿,这个问题你解决了吗?我现在面临同样的问题。尝试关闭连接时代码挂起。
标签: c# winforms serial-port port