gpt4 book ai didi

c# - 每行而不是每个字符的新行?

转载 作者:行者123 更新时间:2023-12-02 05:28:16 24 4
gpt4 key购买 nike

变量 myReceivedLines(下面的代码)从串口接收到的数据为每个字符显示新行,而不是为每个“句子”逐行显示。

有没有办法让“句子”出现在不同的行而不是字符?

   //Fields
string myReceivedLines;

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


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);

SerialPort 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

if ((port.IsOpen) && (connecttodevice == true))
{
port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
DA.SetDataList(0, myReceivedLines);
}

最佳答案

假设您输入包含换行符,请使用 ReadLine为了达成这个。请注意,如果您没有设置正确的 ReadTimeout,它就是一个阻塞调用。我会将 ReceivedBytesThreshold 设置为预期的平均行长度,并将我的行存储在适合我需要的任何集合中。

//Fields
List<string> myReceivedLines;

//subscriber method for the port.DataReceived Event
private void DataReceivedHandler(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
while(sp.BytesToRead > 0)
{
try
{
myReceivedLines.Add(sp.ReadLine());
}
catch(TimeOutException)
{
break;
}
}
}

关于c# - 每行而不是每个字符的新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771271/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com