日期:2014-05-18  浏览次数:20883 次

请教Port通讯问题!!!
代码如下:

C# code

private Queue<string> RobotBy = new Queue<string>(); // received data . robot

private bool SendDataToRobot(string DataStr)
{    
            bool rut = false;
            string sendDataFormat;
            try
            {
                if (!serialPort_Robot.IsOpen)
                {
                    string portName = System.IO.Ports.SerialPort.GetPortNames().Where(pName => (pName == serialPort_Robot.PortName)).First();
                    if (string.IsNullOrEmpty(portName))
                    {
                        WriteLog(string.Format("port '{0}' is denied", serialPort_Robot.PortName));
                        throw new Exception(string.Format("port '{0}' is denied", serialPort_Robot.PortName));
                    }
                    serialPort_Robot.Open();
                }
            }
            catch (Exception err)
            {
                WriteLog(string.Format("Open Robot Port Exception Message:{0}", err.Message));
                throw new Exception(err.Message);
            }
    if (serialPort_Robot.IsOpen && !!string.IsNullOrEmpty(DataStr))
        {
        try{
        serialPort_Robot.DiscardOutBuffer();
                byte[] buf = Encoding.ASCII.GetBytes(DataStr.ToString());
                serialPort_Robot.Write(buf, 0, buf.Length);
        }catch(Exception e)
        {
            throw new Exception("Write Data to Robot Error,message:"+ e.Message);
        }
    }
}

public MainForm()
{
serialPort_Robot.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.SerialPort_RobotDataReceived);
}

private void SerialPort_RobotDataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                RobotBy.Enqueue(serialPort_Robot.ReadTo("\x001a"));
                serialPort_Robot.Close();
            }
            catch (IOException se)
            {
                WriteLog(string.Format(
                    "Robot receivedata {0} : The write operation could not be performed because the specified part of the file is locked.",
                    se.GetType().Name)
                    );
            }
        }



问题在调用 SendDataToRobot(string DataStr) 的时候会出现 "Open Robot Port Exception Message:Access to the port 'COM7' is denied." ,弄了好久没弄好,请教高手..

------解决方案--------------------
也许你COM口关闭了,线程还是再访问这个端口,建议先关闭timer,线程,然后注销端口
------解决方案--------------------
不是同步没做好,重复调用 serialPort_Robot.Open()
------解决方案--------------------
如楼上
你应该把open独立出来,并不是每发送一个数据,就打开一次。一个过程打开一次就可以了,甚至说,程序已运行就新型初始化,然后一直保持打开状态。你发送就好了。