我有一个线程与主窗体(UI)并行运行。它所做的(现在)是每秒增加一个计数器。我想在Windows窗体中使用标签显示计数器的值。那可能吗? 当我尝试下面的代码时,ShowValue方法中出现编译错误。我必须声明ShowValue“static”,以便我可以从后台线程调用它。但如果我这样做,我不能使用“这个”。访问ShowValue Form1中的标签。 这是正确的方法吗? 任何提示将不胜感激,谢谢!如何从C#中的后台线程刷新Windows窗体中的标签?
private void count_secs()
{
while (!stopThread)
{
if (stopThread)
{
break;
}
num2++; // increment counter
Form1.ShowValue(num2); // display the counter value in the main Form
try
{
Thread.Sleep(1000); // wait 1 sec.
}
catch (ThreadInterruptedException)
{
if (stopThread)
{
break;
}
}
}
}
然后在我的Form1类中,我有:
public static void ShowValue(int num)
{
this.label7.Text = num.ToString();
// compiler error here: "Keyword 'this' is not valid in a static method.
}
很好的回答,使用'BeginInvoke'就是这样做的方法。 – Jeremy 2013-05-08 07:34:03