c#串行端口

本文关键字:串行端口 | 更新日期: 2023-09-27 18:17:36

我的伪代码是…

GetData_1()向串口发送请求,收到应答后,GetData_2()发送另一个请求。接收到第二个请求的响应后,所有接收到的数据一起插入到数据库中。然后再次调用GetData_1()以递归地继续此过程…

但……我得到堆栈溢出流的错误…请帮助…

 GetDat_1()
{
//Send a request To SerialPort
//wait a 500 ms.
// read The response and insert it into an array...
GetData_2();
}
GetData_2()
{
// Send a request to SerialPort
// Wait a 500 ms.
// Read The response and insert it into another array
InsertAllData();
GetData_1();
}
InsertAllData()
{
// insert all data into the database
}

c#串行端口

这是因为重复的调用永远不会返回,调用堆栈只是不断增长,导致StackOverFlowException迟早,很可能早。

相反,展开到一个迭代的编码方式。

while (!done)
    // GetDat_1 is inlined here
    // Send a request To SerialPort 
    // wait a 500 ms.
    // read The response and insert it into an array...
    // GetData_2 is inlined here
    // Send a request to SerialPort
    // Wait a 500 ms.   
    // Read The response and insert it into another array
    InsertAllData();
}

GetData_1()调用GetData_2(), GetData_2()调用GetData_1(), GetData_1()调用GetData_2()…以此类推,直到堆栈溢出。

你需要重新设计你的方法以另一种方式工作

也许在这种情况下使用某种类型的循环会更好。

分别调用GetData_1()GetData_2(),这是一个死循环。由于任何方法调用都会在线程的堆栈中"记录"一些数据(方法参数等),因此不定式调用会导致堆栈溢出,因为堆栈不是无限的。

问题与串行端口无关。这可以通过

轻松复制
Getdata_1()
{
Getdata_2();
}
Getdata_2()
{
GetData_1();
}

和其他的。

没有简单的解决办法。您需要阅读有关递归的内容,并相应地调整您的算法。

您可以尝试这个示例代码,删除GetData1GetData2方法

while (true)
{
   //Send a request To SerialPort  
   //wait a 500 ms.  
   // read The response and insert it into an array... 
   // Send a request to SerialPort  
   // Wait a 500 ms.  
   // Read The response and insert it into another array 
   InsertAllData();
   if (/*set true if i want to end the loop*/)
      break;
}

我会这样做:

while(!done)
{
    //Send request
    GetData_1();
    //Send request
    GetData_2();
    InsertAllData();
}

虽然我会设置一个中断从串行端口收集数据