【发布时间】:2021-05-19 15:06:41
【问题描述】:
我是 C# 的初学者,想要一些关于如何解决以下问题的建议:
我的主要代码包括2个线程,第一个线程用于发送数据,第二个用于从串口读取数据。我用 sinh=1;变量以同步两个线程。 sinh = 1 的第一个线程发送第一个寄存器的寄存器名称和读取命令并设置 sinh = 2。然后第二个线程读取数据并设置 sinh = 3。然后 sinh = 3 的第一个线程发送寄存器名称和第二个读取命令注册并设置sinh = 4。最后,sinh = 4 处的第二个线程读取数据并设置sinh = 1,一切都再次重复。
问题是第二个线程没有按应有的方式读取数据。在开始发送和读取工作在几个周期后同步读取数据(应写入 sin = 2 的数据写入 sihn = 4,应写入 sin = 4 的数据写入 sihn = 2),然后它再次正常工作几个周期,然后再次混合所有数据等等。
我正在解决这个问题好几天了,我不知道该怎么办。
第一个线程(发送数据):
private void read()
{
while (read_data_on)
{
if (sinh == 1 )
{
serialPort1.Write(new byte[] { 0x55, 0x40, 0x05 }, 0, 3); //set register 1
serialPort1.Write(new byte[] { 0x55, 0x1c }, 0, 2); //read register 1
sinh = 2;
}
if (sinh == 3 )
{
serialPort1.Write(new byte[] { 0x55, 0x40, 0x65 }, 0, 3); //set register 2
serialPort1.Write(new byte[] { 0x55, 0x1c }, 0, 2); //read register 2
sinh = 4;
}
}
第二个线程(接收数据):
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (sinh == 2 ) //read register 1
{
byte[] input1 = new byte[3];
int st_bajtov1 = serialPort1.Read(input1, 0, 3);
vrednost1 = (input1[2] << 16) | (input1[1] << 8) | (input1[0]);
sinh = 3;
}
if (sinh == 4 ) //read register 2
{
byte[] input2 = new byte[3];
int st_bajtov2 = serialPort1.Read(input2, 0, 3);
vrednost2 = (input2[2] << 16) | (input2[1] << 8) | (input2[0]);
sinh = 1;
}
}
【问题讨论】:
标签: c# multithreading while-loop serial-port