C# SerialPort类和DataReceived事件。。。获取字节。使用ReadLine还是ReadExisting?有什么例子吗?
我想通过串口发送和接收字节。我的接收器应该异步获取字节。我在下面写了一个小例子,看起来很有效,但它让我感到不安C# SerialPort类和DataReceived事件。。。获取字节。使用ReadLine还是ReadExisting?有什么例子吗?,c#,asynchronous,serial-port,C#,Asynchronous,Serial Port,我想通过串口发送和接收字节。我的接收器应该异步获取字节。我在下面写了一个小例子,看起来很有效,但它让我感到不安 我真的应该使用WriteLine、ReadLine吗?正如现在所写的,事件处理程序m_port_DataReceived中的代码是否可能为每个字节调用?这就是我对“DataReceived”事件的理解;也许我错了。ReadLine是否会阻止,直到它看到一个行尾字符 我是否应该在事件处理程序中使用“if(e.EventType==SerialData.Eof)”构造?你可以看到我已经把它
假设属性receivedBytestThreshold=1(这是默认值,并且您似乎没有对其进行更改),那么当至少有1个字节要接收时,DataReceivedEvent将触发。可能还有更多。这与接收到的每个字节的事件触发不同。这意味着当它触发时,至少会有1个字节。我一直使用的方法没有问题,就是在DataRcvd处理程序触发时将数据作为字节数组读取。我将字节数组的缓冲区推到队列中。当我需要这些数据时,我会把它们拼凑在一起,然后使用它们/转换它们。。。根据应用程序的不同,我会执行以下操作之一:1-DataRcvd处理程序在UI线程上引发事件;2-使用定时器;DataRcvd处理程序调用UI线程上的一个方法。我这样做了,但是处理程序没有很好的响应。对于每次接收的数据,它只识别大约10个接收到的数据中的1个。你知道为什么吗?@ConradC不确定。。但是你说了1/10次触发器上的事件,如果你读了ReadExisting,你就丢失了数据?是不是你的缓冲区太小了?我想我明白了。我同时使用了一个读取线程和DataReceivedHandler,我想这会引起冲突。
public class SerialPortController
{
SerialPort m_port;
public SerialPortController(bool server)
{
if (server)
{
m_port = new SerialPort("COM4");
m_port.BaudRate = 115200;
m_port.Open();
byte[] sillyBytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 };
ASCIIEncoding encoding = new ASCIIEncoding();
string output_string = encoding.GetString(sillyBytes);
m_port.WriteLine(output_string);
//m_port.Write(sillyBytes, 0, 8);
}
else
{
m_port = new SerialPort("COM5");
m_port.DataReceived += new SerialDataReceivedEventHandler(m_port_DataReceived);
m_port.BaudRate = 115200;
m_port.Open();
}
int character = Console.Read();
}
void m_port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//if (e.EventType == SerialData.Eof)
{
// string answer = m_port.ReadExisting();
string answer = m_port.ReadLine();
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte_answer = encoding.GetBytes(answer);
}
}
}
private static void DataReceviedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.Write(indata);
}