C# 在serialport data received事件中,它表示由于线程退出或应用程序请求,I/O操作已中止
我正在为我的物联网项目将VS和Arduino IDE集成在一起。我必须读取数据并将其显示在VS IDE中,我可以这样做。在串行数据接收事件中,仅读取前3个值,而不读取其他3个值。以前我可以读取数据,但不能显示它。我得到的错误是交叉线程,我用委托纠正了这个错误。现在我不识字了。 异常:System.IO.IOException:'由于线程退出或应用程序请求,I/O操作已中止C# 在serialport data received事件中,它表示由于线程退出或应用程序请求,I/O操作已中止,c#,visual-studio,serial-port,ioexception,C#,Visual Studio,Serial Port,Ioexception,我正在为我的物联网项目将VS和Arduino IDE集成在一起。我必须读取数据并将其显示在VS IDE中,我可以这样做。在串行数据接收事件中,仅读取前3个值,而不读取其他3个值。以前我可以读取数据,但不能显示它。我得到的错误是交叉线程,我用委托纠正了这个错误。现在我不识字了。 异常:System.IO.IOException:'由于线程退出或应用程序请求,I/O操作已中止 VS Code private void serialPort1_DataReceived(object sender,
VS Code
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
Microsoft.VisualBasic.Interaction.MsgBox("dfghjk");
moist = serialPort1.ReadLine(); //can read
temper = serialPort1.ReadLine(); //can read
humid = serialPort1.ReadLine(); //can read
SetTextMo(moist); //can set
SetTextTe(temper);//can set
SetTextHu(humid);//can set
resMois = serialPort1.ReadLine(); //cannot read (exception mentioned above occurs)
resTemp = serialPort1.ReadLine(); //cannot read (exception mentioned above occurs)
resHumi = serialPort1.ReadLine(); //cannot read (exception mentioned above occurs)
SetTextResM(resMois); //can set
SetTextResT(resTemp);//can set
SetTextResH(resHumi); //can set
}
只是猜测一下,您可能正在不同的数据包中发送checkCurrentValue()和checkParameters()数据,因此事件可能会触发两次。如果
e.EventType==SerialData.Eof
,请检入事件处理程序,如果是,则不再读取。当下一个数据包到达时,您的事件处理程序可能会被触发。您是否有main方法?只是猜测,但是,您可能正在不同的数据包中发送checkCurrentValue()和checkParameters()数据,因此事件可能会被触发两次。如果e.EventType==SerialData.Eof
,请检入事件处理程序,如果是,则不再读取。当下一个数据包到达时,您的事件处理程序可能会被触发。您有main方法吗?
Arduino Code
void loop()
{
if(a == 0)
{
if(Serial.available() > 0)
{
mySt = Serial.readString();
i = mySt.toInt();
if (i==1)
{
checkCurrentValue();//works perfect
suitablePlant();//works perfect
a++;
}
else if(i==2)
{
crop = Serial.readString();
checkCurrentValue();//values of the data i can read belong too this function
checkParameters();//values of data belonging to this function i am unable to read
a++;
}
else{}
}
}
}