我有一个与主窗体 (UI) 并行运行的线程。它所做的(目前)只是每秒增加一个计数器。我想在 Windows 窗体中使用标签显示计数器的值。那可能吗?当我尝试以下代码时,在 ShowValue 方法中出现编译错误。我必须将 ShowValue 声明为“静态”,以便我可以从后台线程调用它。但如果我这样做,我就不能使用“这个”。访问 ShowValue Form1 中的标签。这是正确的方法吗?任何提示将不胜感激,谢谢!
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.
}