2011-12-13 104 views
0

我的僞代碼是這樣的......堆棧溢出的serialport上

的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 
} 
+1

代碼剛剛壞掉,你從GetData2中調用GetData1。其中調用GetData2調用GetData1。其中調用GetData2 ... * Kaboom!* –

+0

@HansPassant它是這樣的問題,真的給這個網站它的名字:) –

+0

+1獲得StackOverFlowException並詢問它在stackoverflow.com – vidstige

回答

2

這是因爲重複的調用永遠不會返回,調用堆棧不斷增加,最終導致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(); 
} 
+0

謝謝你vidstige ... –

+0

感謝我的答案。這個答案的左邊有一個綠色概述複選框。如果我的回答幫助你,請點擊它。提前致謝。 – vidstige

2

GetData_1()調用GetData_2(),它會調用GetData_1(),它將永遠調用GetData_2()等等,直到你達到堆棧溢出爲止。

你需要重新設計你的方法以另一種方式

工作也許使用某種類型的在這種情況下的循環會更好。

+0

謝謝你jon c .. –

1

GetData_1()GetData_2()調用每一個,所以這是一個死循環。由於任何方法調用「記錄」線程堆棧中的某些數據(方法參數等),這種不定式調用會導致堆棧溢出,因爲堆棧不是無限的。

0

該問題與串口無關。這可以很容易地複製只是

Getdata_1() 
{ 
Getdata_2(); 
} 

Getdata_2() 
{ 
GetData_1(); 
} 

而沒有別的。

有沒有簡單的解決方案。你需要閱讀關於遞歸併相應地調整你的算法。

+0

謝謝liho 1eye .. –

0

您可以嘗試此示例代碼,刪除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; 
} 
+0

謝謝你Onesimus Unbound .. –

0

我會做:

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

雖然我會成立一箇中斷收集來自數據串行端口。

+0

謝謝jeff .... –