user971741
user971741

Reputation:

Progress bar not incrementing

I have the following code which read a file and also increment the progress bar while reading it, but I don't see any activity in my progressBar. Why is this?

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;

    }

 }

Upvotes: 0

Views: 1244

Answers (3)

Shamim
Shamim

Reputation: 444

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

Upvotes: 0

Anjan
Anjan

Reputation: 31

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

Upvotes: 0

GrzegorzM
GrzegorzM

Reputation: 842

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.

Upvotes: 2

Related Questions