2011-02-03 109 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); 
}