无法关闭和重新打开通信端口RS232

时间:2017-01-21 12:40:57

标签: c# serial-port port

我正在尝试使用RS232 com端口将重量附加到计算机上。

我可以阅读称重,但当我走出表格时,又来了 -

我的程序和计算机冻结。

这是我的代码:

private void Main_Load(object sender, EventArgs e)
{ 
    port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
    port.DataReceived += new s system.IO.Ports.SerialDataReceivedEventHandler(Recepcion);

    if (port.IsOpen == false)
    {
      try
      {
         port.Open();
      }
      catch (Exception oex)
      {
          MessageBox.Show(oex.ToString());
      }
    }
}


private void Actualizar(object s, EventArgs e)
{
   //I try this
   lblMSG.Text = ExtractDecimalFromString(port.ReadLine()).ToString();
   port.DiscardInBuffer();

   //Also I try this
   lblMSG.Text = ExtractDecimalFromString(port.ReadExisting()).ToString();
   port.DiscardInBuffer();
}


private void Recepcion(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
  try
  {
     this.Invoke(new EventHandler(Actualizar));
  }
  catch { }
}

当我关闭表单时,我这样做:

 port.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(Recepcion);

GC.Collect();   //also i try to remark this
port.Close();
port.Dispose();
this.Close();

它并不总是冻结,有时是......有时候没有......

我搜索整个网络仍然没有回答和解决方案。

我真的很绝望。我希望在这里找到解决方案

1 个答案:

答案 0 :(得分:0)

您是否尝试使用外部USB串行适配器(而不是COM1)来排除硬件问题?

不应该在port.Close()和port.Dispose()之后运行GC.Collect()。

哪个代码行导致冻结?

相关问题