Progress Bar not incrementing

北慕城南 提交于 2019-12-23 04:38:09

问题


I have the following code which read a file and also increment te progress bar while reading it, but i dont see any activity in my progressBar. can anyone please help me why?

progressBar1.Minimum = 0;
progressBar1.Maximum = (int)fileStream.Length + 1;
progressBar1.Value = 0;

using (fileStream)
{
    fileStreamLength = (int)fileStream.Length + 1;
    fileInBytes = new byte[fileStreamLength];
    int currbyte = 0, i = 0;
    var a = 0;
    while (currbyte != -1)
    {
        currbyte = fileStream.ReadByte();
        fileInBytes[i++] = (byte)currbyte;
        progressBar1.Value=i;

    }

 }

回答1:


It is incrementing but you cannot see it. It is caused by running your loop in UI thread. Look for BackGroundWorker or async/await pattern.




回答2:


User Method Invoker to update the UI... try this...

Do all the your work in a thread and when updating the progressbar use the following lines...

For Windows Forms

this.Invoke((MethodInvoker) delegate
{
progressBar1.value=i;
});

For WPF

Dispatcher.BeginInvoke(new Action(delegate
{
progressBar1.value=i;
}));



回答3:


your best option will be Background Worker.
drag and drop a BackgroundWorker from toolbox. then you have to implement 2 function: one is doing the background work, another is for reporting to UI.

using System.ComponentModel;
using System.Threading;

public partial class Form1 : Form
{
public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, System.EventArgs e)
{
    // Start the BackgroundWorker.
    backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
        // begin reading your file here...

        // set the progress bar value and report it to the main UI
        int i = 0; // value between 0~100
        backgroundWorker1.ReportProgress(i);
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // Change the value of the ProgressBar to the BackgroundWorker progress.
    progressBar1.Value = e.ProgressPercentage;
    // Set the text.
    this.Text = e.ProgressPercentage.ToString();
}
}


来源:https://stackoverflow.com/questions/20173638/progress-bar-not-incrementing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!