2011-02-03 47 views
-3

我的代碼中存在什麼問題?while循環中的線程問題

 private void button1_Click(object sender, EventArgs e) 
    { 
     int i = 0; 
     ParameterizedThreadStart start = new 
     ParameterizedThreadStart (gh); 

     Thread.CurrentThread.Priority = ThreadPriority.Lowest; 

     Thread u = new Thread(start); 
     u.Priority = ThreadPriority.Highest; 

     while (i < 100) 
     { 
      if (u.IsBackground) 
      { 
       while (u.IsBackground) 
       { 
        if (!u.IsBackground) break; 
       } 
      } 
       u = new Thread(start); 

       i++; 
       u.Start(i); 

      System.Threading.Thread.Sleep(10); 
     } 
    } 


    void gh(object e) 
    { 
     if (InvokeRequired) 
     { 
      b = delegate() 
      { 
       label1.Text = string.Format("Step is :{0}", e.ToString());  
      }; 
      Invoke(b); 
     } 
     else label1.Text = string.Format("Step is :{0}", e.ToString());  
    } 

}

+1

添加語言標記 – ThomasMcLeod 2011-02-03 16:36:16

回答

2

你需要提供什麼錯,或者沒有做你所期望的一些更多的信息。您可以從整理代碼和添加評論中受益。其中有些並不合理。例如:

if (u.IsBackground) { 
    while (u.IsBackground) 
    { 
     if (!u.IsBackground) 
      break; 
    } 
} 

所有這些代碼是做同樣的事情 - 在等待u.IsBackground成爲虛假時吃的CPU。這整個塊就像是這樣做的:

while (u.IsBackground) { } 

然而,這是不好的做法來創建這樣的循環,因爲他們只會吃起來的資源不斷評估。你至少應該添加一個暫停,以顯着減少資源,使用,例如:

// Wait until the thread is no longer running in the background 
while (u.IsBackground) 
{ 
    // Sleep for 50 milliseconds before checking again, to avoid eating CPU. 
    Thread.Sleep(50); 
}