我的代码中有什么问题?
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());
}
}
答案 0 :(得分: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);
}