Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法关闭和重新打开通信端口RS232_C#_Serial Port_Port - Fatal编程技术网

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

C# 无法关闭和重新打开通信端口RS232,c#,serial-port,port,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.SerialDataR

我正试图通过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();
它并不总是冻结,有时是的…有时不是

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


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

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

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


哪个代码行导致冻结?

什么这么复杂?没有解决方案?我使用USB到COM电缆。我将其标记为:GC.Collect(),冻结导致在port.Close()中出现;你找到解决问题的办法了吗?你试过另一台电脑吗?可能是因为你从UI线程执行关闭操作。。。