2014-08-30 72 views
0
public void serialcek() 
    { 

      while (!exitThread) 
      { 
       foreach (ManagementObject currentObject in theSearcher.Get()) 
       { 

        try 
        { 
         textBox1.Text = currentObject["Size"].ToString() + " " + currentObject["PNPDeviceID"].ToString(); 
         currentObject.Dispose(); 

        } 
        catch (Exception) 
        { 
         // MessageBox.Show("Bişiler oldu bende anlamadım"); 
         currentObject.Dispose(); 
         //exitThread = false; 
        } 
       } 

      } 
      Thread.Sleep(100); 
      serialcek(); 
     } 

我使用線程。但是幾分鐘後它出現了一個錯誤。點擊按鈕是exitThread成真。比5分鐘後給一個StackOverflowException是未處理的HResult = -2147023895錯誤。StackOverflowException未處理HResult = -2147023895

感謝您的幫助。

+2

因爲您呼叫serialchek()遞歸沒有退出條件。 – OldProgrammer 2014-08-30 14:26:34

回答

2

你的調用serialcek()遞歸沒有停止,並導致堆棧溢出。

P.s.使用finallytry\catch防止重複代碼:

public void serialcek() 
{ 

     while (!exitThread) 
     { 
      foreach (ManagementObject currentObject in theSearcher.Get()) 
      { 
       try 
       { 
        textBox1.Text = currentObject["Size"].ToString() + " " + currentObject["PNPDeviceID"].ToString(); 
       } 
       catch (Exception) 
       { 
        // MessageBox.Show("Bişiler oldu bende anlamadım"); 
        //exitThread = false; 
       } 
       finally 
       { 
        currentObject.Dispose(); 
       } 
      } 
     } 
     Thread.Sleep(100); 

     if(<condition>) // add your condition here 
     { 
      serialcek(); 
     } 
    } 
相關問題