以下代码构建没有错误,但是当我运行程序时,接收的数据不会显示在输出中。当我在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();
}
答案 0 :(得分:1)
SerialPort的DataReceived事件在与UI线程不同的线程上运行。您需要执行类似DataReceived事件建议的MSDN页面。您获得访问被拒绝错误的原因是因为端口仍处于打开状态,重新启动计算机以正确重新启动程序是不够的。
即。来自上面的链接
private static void DataReceivedHandler( object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
}