2016-04-14 178 views
2

我一直在为机器编写一些代码。 它必须说RS485,我可以使用正常的串行通信为它提供.net在com端口c上拒绝访问#

但是,由于硬件可能会失败,我必须建立测试例程。 所以我写了重新检测可用comports的例程。 使用它们的字符串名称填充列表'allComPorts',然后使用数字上下按钮选择基于其可用comports的列表索引的com端口。 (是的,这听起来有点复杂,但由于其他原因,我已经使用数字更新选择)。

问题是这个函数只有第一次。 如果我再次调用该函数,我会得到一个拒绝访问,因为它的接缝已经打开。尝试RS485Port.Close()在不同的地方,但如果它没有打开jet(鸡蛋问题),问题就会变成崩溃。

我的代码打开一个水果盘是这样

private void RS485Activate() 
    { 
      lblNoRS485Communication.Visible = false; 
     if (cmbRS485Port.Value != 0) // if 0 then there are no serial ports 
     { 
      //rs485Port is a global declared as > System.IO.Ports.SerialPort RS485Port; 
      RS485Port = new System.IO.Ports.SerialPort(allComPorts[(int)cmbRS485Port.Value - 1]); 
      if (!RS485Port.IsOpen) 
      { 
       // RS485Port.Close(); 
       // RS485Port = new System.IO.Ports.SerialPort(allComPorts[(int)cmbRS485Port.Value - 1]); 
       RS485Port.BaudRate = 9600; 
       RS485Port.Parity = System.IO.Ports.Parity.None;     
       RS485Port.StopBits = System.IO.Ports.StopBits.One;    
       RS485Port.DataBits = 8;           
       RS485Port.Handshake = System.IO.Ports.Handshake.None;   
       RS485Port.RtsEnable = true; 
       RS485Port.Open(); <== it crashes here with access denied 
      } 
     } 
     else 
     { 
      MessageBox.Show("There is no COM port detected, the program will work but it cannot control any machinery", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
      lblNoRS485Communication.Visible = true; // another warning 
     } 
    } 
+0

你检查,如果该端口没有被另一个进程使用? –

+0

以前它已经被打开了,但是对于测试我不能认为这个(其他的事情可能已经影响到了机器) ,因为我不能测试像:'if(RS485Port!= Null)RS485Port。关闭();'我想知道如何解决它 – user3800527

+0

调用Close()不会使端口可用立即。有一个需要退出的工作线程,即生成DataReceived和ErrorReceived事件的线程。需要多长时间是不可预测的。但你肯定可以从例外中知道:)睡一会儿再试一次。不要试图永远,因为它可能实际上是另一个已经声称该港口的过程。 –

回答

0

我不喜欢这个长相,所以我希望有一个更好的办法。 但是作为一种解决方法,使用try catch结构,它现在首先尝试关闭,(try-catch可以防止close()错误,如果它还没有初始化,那么我不喜欢这个解决方法,所以更好解决方案是值得欢迎的,我不认为代码应该预见并基于错误。(或者是确定这些天.NET?)

  //...     
      try 
      { RS485Port.Close(); } 
      catch 
      { } 
      RS485Port = new System.IO.Ports.SerialPort(allComPorts[(int)cmbRS485Port.Value - 1]); 
      if (!RS485Port.IsOpen) 
      { 
       // RS485Port.Close(); 
       // RS485Port = new System.IO.Ports.SerialPort(allComPorts[(int)cmbRS485Port.Value - 1]); 
       RS485Port.BaudRate = 9600; 
       RS485Port.Parity = System.IO.Ports.Parity.None;   
       RS485Port.StopBits = System.IO.Ports.StopBits.One;  
       RS485Port.DataBits = 8;          
       RS485Port.Handshake = System.IO.Ports.Handshake.None;  
       RS485Port.RtsEnable = true; 
       RS485Port.Open(); 
      }