0

以下代码正在构建且没有错误,但是当我运行程序时,接收到的数据未显示在输出中。当我在上放置断点时,myReceivedLines = port.ReadExisting();我得到:

System.InvalidOperationException.

在程序本身中,重新启动我的计算机后它说:

Access to COM5 is denied

我能做些什么来解决这个问题?

代码:

//Fields
SerialPort port;
string myReceivedLines;

   protected override void SolveInstance(IGH_DataAccess DA)
  {

    List<string> gcode = new List<string>();
    DA.GetDataList(0, gcode);
    string selectedportname = default(string);
    DA.GetData(1, ref selectedportname);
    int selectedbaudrate = default(int);
    DA.GetData(2, ref selectedbaudrate);
    bool connecttodevice=default(bool);
    DA.GetData(3, ref connecttodevice);
    bool sendtoprint= default(bool);
    DA.GetData(4, ref sendtoprint);


    if (!DA.GetDataList(0, gcode)) return;
    if (!DA.GetData(1, ref selectedportname)) return;
    if (!DA.GetData(2, ref selectedbaudrate)) return;
    if (!DA.GetData(3, ref connecttodevice)) return;
    if (!DA.GetData(4, ref sendtoprint)) return;


    port = new SerialPort(selectedportname, selectedbaudrate, Parity.None, 8, StopBits.One); //Create the serial port
    port.DtrEnable = true;   //enables the Data Terminal Ready (DTR) signal during serial communication (Handshaking)
    port.Open();             //Open the port
    port.DataReceived += this.portdatareceived;


    if (gcode == null)
    {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Specify a valid GCode");
        return;
    }

    if (connecttodevice == true)
    {
        DA.SetDataList(0, myReceivedLines);
    }

        if (sendtoprint == true)
        {
            foreach (String s in gcode)
            {
                port.WriteLine(s);
            }
        }

              }


    //subscriber method for the port.DataReceived Event
    private void portdatareceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
            myReceivedLines = port.ReadExisting();
    }
4

1 回答 1

1

SerialPort 的 DataReceived 事件在与 UI 线程不同的线程上运行。您将需要执行类似 MSDN Page for The DataReceived Event 建议的操作。您收到拒绝访问错误的原因是因为端口仍然打开,重新启动计算机以纠正重新启动程序是不够的。

即来自上面的链接

private static void DataReceivedHandler( object sender, SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    string indata = sp.ReadExisting();
}
于 2012-10-07T01:58:31.263 回答