简体   繁体   中英

C# Progressbar & Textbox Not Updating

I've seen some great answers here and was wondering if someone could help me out.

Here's my code:

namespace expandGUIWPF
{

        public static string getSHA256b64(string filepath)
        {
            byte[] bytes = SHA256.Create().ComputeHash(File.ReadAllBytes(filepath));
            return Convert.ToBase64String(bytes);
        }

        private void btnRun_Click(object sender, RoutedEventArgs e)
        {
            {
                string folder = txtFolder.Text;
                string filelist = folder + "\\FileList.txt";
                string[] test = Directory.GetFiles(folder, "*", System.IO.SearchOption.AllDirectories);
                File.WriteAllLines(filelist, test);


                int length = File.ReadLines(filelist).Count();
                pBar1.Minimum = 1;
                pBar1.Maximum = length;

                File.WriteAllLines(filelist, test);

                using (StreamReader sr = new StreamReader(filelist))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        string oldfile = line;
                        string newfile = oldfile + ".expanded";
                        string oldhash = "";
                        string newhash = "";

                        try
                        {
                            ProcessStartInfo startInfo = new ProcessStartInfo(@"C:\test\test.exe", oldfile + " " + newfile);
                            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                            Process.Start(startInfo);

                            Thread.Sleep(1000);

                            if (File.Exists(oldfile))
                            {
                                oldhash = getSHA256b64(oldfile);
                            }
                            if (File.Exists(newfile))
                            {
                                newhash = getSHA256b64(newfile);
                                File.Delete(oldfile);
                                File.Move(newfile, oldfile);
                            }

                            pBar1.Value = pBar1.Value + 1;

                            txtLog.AppendText(oldfile + "\r\n   Old: " + oldhash + "\r\n   New: " + newhash + "\r\n");
                            if (!(oldhash == newhash))
                            {
                                txtLog.AppendText("Successfully expanded file \r\n");
                            }
                            else
                            {
                                txtLog.AppendText("Unable to expand file \r\n");
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                }
            }
        }
    }
}

The problem is that my progressbar isn't updating. I know a little C# but I'm a beginner to WPF and can't get my head around setting up a background worker to update my UI. Would someone be able to give me a few pointers please? Currently the app works fine, but the progressbar jumps to 100% finished and all of the text suddenly appears.

Thanks in advance!

Tom

First you'll want your background worker to handle the processes in its DoWork event. Within that event you can call the ProgressChanged event to update the progress bar. Below is an example:

    private void btnRun_Click(object sender, RoutedEventArgs e)
    {
        if(workerThread.IsBusy == false)  // Make sure someone doesn't click run multiple times by mistake
        {
            pBar1.Value = 0;
            workerThread.RunWorkerAsync();
        }
    }

    private void workerThread_DoWork(object sender, DoWorkEventArgs e)
    {
        // Definitions and so forth
        pBar1.Minimum = 0;
        pBar1.Maximum = length;
        int status = 0;
        using (StreamReader sr = new StreamReader(filelist))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                // Try/Catch work here
                status++;
                workerThread.ReportProgress(status);
            }
    }

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

Just understand that the thread that's running the Form is the same one that will be used to update the form's controls. So if you have 'stuff' to do - like encrypting / decrypting lines from a file - you need to perform those items on another thread with a callback, otherwise the form display wont update until it's done with your stuff to do. You can raise events from inside a worker thread -- and catch them using an event handler on the main (form) thread to update the progress bar.

It seems that your UI thread is being blocked, in windows forms programming you have one message pump and while you main thread (UI) is doing something else it has to wait before it can process messages. You can fix this problem by setting up a background worker to send updates

For more information on UI thread and the message pump see this

http://www.codeproject.com/Articles/10311/What-s-up-with-BeginInvoke

For infomation on the backgroundworker thread see this

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

Small Example code

// This event handler is where the time-consuming work is done. 
     private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
     {
        BackgroundWorker worker = sender as BackgroundWorker;

        for (int i = 1; i <= 10; i++)
        {
            if (worker.CancellationPending == true)
            {
                e.Cancel = true;
                break;
            }
            else
            {
                // Perform a time consuming operation and report progress.
                System.Threading.Thread.Sleep(500);
                worker.ReportProgress(i * 10);
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM