簡體   English   中英

C#填充進度條在單獨的線程中

[英]C# Filling progress bar in separate thread

我有一個進度條,想用一個單獨的線程來填充它,因為主線程循環進入休眠狀態幾秒鍾。 我使用計時器,以便進度條在一定時間內充滿。

線程創建:

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循環之前/期間填充,即使我在for循環之前調用fillbar()環。

線程方法:

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();
            }

        }

你這樣做是錯誤的。 主線程負責更新用戶界面。 因此,如果您用計算來阻止它,它將無法繪制進度條。 將計算代碼移到另一個線程中,應該沒問題。

始終是管理用戶界面的主線程。 為此使用backgroundworker 要啟用backgroundworker中的進度功能,請將WorkerReportProgress(property)設置為true,並設置WorkerSupportCancellation以便在需要時停止backgroundworker。

  private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
         // also use sender as backgroundworker
        int i = 0;
        foreach (MusicNote music in this.staff.Notes)
        {
            if(backgroundWorker1.CancellationPending) return;
             music.Play(music.Dur);
            Thread.Sleep(music.getInterval(music.Dur));

            int p =  (int) (i*100/ staff.Notes.Count); /*Count or Length */
            backgroundWorker1.ReportProgress(p);
            i++;
        }
        backgroundWorker1.ReportProgress(100);
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM