我正在學習使用線程並進行一些多線程演示。
我有一個名爲lblText的標籤和一個名爲pgbRun的選取框進度條。我製作了2個線程,一個讓標籤的文本在每個Thread.Sleep()
調用後更改,其他讓標籤的文本更改時進度條顯示動畫。
我遇到的問題是文本更改線程似乎工作正常,但進度條線程有問題。 pgbRun剛剛開始動畫後文本更改完成。
請幫我看看我的代碼有什麼問題,並告訴我一些解決問題的方法。非常感謝!跑馬燈進度條有問題
private delegate void formDelegate();
private void btnRun_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(new formDelegate(textChange)));
thread.IsBackground = true;
thread.Start();
}
public void textChange()
{
if (lblText.InvokeRequired)
{
lblText.BeginInvoke(new formDelegate(textChange));
}
else
{
Thread thread = new Thread(new ThreadStart(new formDelegate(progess)));
thread.IsBackground = true;
thread.Start();
//I try make single thread that config progress bar here but i have same trouble.
for (int i = 0; i < 10; i++)
{
lblText.Text = "Count: " + i;
lblText.Update();
lblText.Refresh();
Thread.Sleep(300);
}
}
}
public void progess()
{
if (pgbRun.InvokeRequired)
{
pgbRun.BeginInvoke(new formDelegate(progess));
}
else
{
pgbRun.Style = ProgressBarStyle.Marquee;
pgbRun.MarqueeAnimationSpeed = 20;
pgbRun.Update();
pgbRun.Refresh();
}
}
你的線程沒有做任何有用的事情,他們立即調用到UI線程。 textChange()代碼不能完成更多的事情,但會導致UI掛起3秒鐘。您可以看到標籤更改,因爲您調用Update()。 projss()中的BeginInvoke()調用在UI線程忙於睡眠3秒內停滯不前,因此您沒有看到進度條發生任何事情。你需要拋棄這些代碼。 –
@HansPassant,我該如何解決它? – tungns304