我有一個線程與主窗體(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