我有一個進度條,並希望使用單獨的線程填充它,因爲主線程在循環中放置了幾秒鐘。我正在使用計時器,以便進度條填滿一定的時間。C#在單獨線程中填充進度條
線程創建:
private void PlayButton_Click(object sender, EventArgs e)
{
progressBar1.Value = 0;
int playTime = getPlayTime();
int progressInterval = playTime/100;
Thread progressThread = new Thread(barfiller=>fillBar(progressInterval));
progressThread.Start();
//Loops through the collection and plays each note one after the other
foreach (MusicNote music in this.staff.Notes)
{
music.Play(music.Dur);
Thread.Sleep(music.getInterval(music.Dur));
}
progressThread.Abort();
}
原樣,沒有任何反應進度條,但如果我調用主線程中fillbar(),它的作品,但它填補後的for循環完成,而不是之前/在for循環中,即使我在循環之前調用了fillbar()。
Thread方法:
private void fillBar(int progressInterval)
{
progressTimer = new System.Windows.Forms.Timer();
progressTimer.Tick += new EventHandler(clockTick);
progressTimer.Interval = progressInterval; //How fast every percentage point of completion needs to be added
progressTimer.Start();
}
public void clockTick(object sender, EventArgs e)
{
if (progressBar1.Value < 100)
{
progressBar1.Value++;
}
else
{
progressTimer.Stop();
}
}
winforms? WPF? Silverlight的? (etc) – 2011-12-27 16:50:16
@ Muad'Dib從'Timer'類型和'Click'處理程序簽名來看,它是WinForms。 – 2011-12-27 16:59:13
使用BackGroundWorker,就是這麼做的。 – TheBoyan 2011-12-27 17:00:00