0

I allready see lot's of questions and posts about progressbars and multithreading, so I hope I am not asking a question that is somewhere else allready answered. But if I did, my appologies, I tried to find a solution.

I have some large files in which I would like to replace & by & Because these files are large I would like te see a statusupdate every now and then how far the document has parsed. The code I've written works for the purpose of replacing the ampersands, however, progress updates are done only after the document has parsed. Any ideas what's wrong?

using System;
using System.Windows;
using Microsoft.Win32;
using System.Text;
using System.Xml;
using System.IO;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Data;
using System.Text.RegularExpressions;
using System.ComponentModel;

namespace DigiPort
{
    public partial class MainWindow : Window
    {

        public string filename;
        public string xmlfilename;
        BackgroundWorker worker = new BackgroundWorker();

        public MainWindow()
        {
            InitializeComponent();
        }

        private void onImportDocClicked(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Text documents (.txt)|*.txt";
            Nullable<bool> result = ofd.ShowDialog();
            if (result == true)
            {
                OutPutWindow.Text = "Document wordt nu gelezen.";
                filename = ofd.FileName;
                worker.DoWork += new DoWorkEventHandler(ReplaceAmpersandAsync);
                worker.ProgressChanged += new ProgressChangedEventHandler(ProBarChanged);
                worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ReplaceAmpersandCompleted);
                worker.WorkerReportsProgress = true;
                worker.ReportProgress(0, "Start counting lines");
                int count = ReadNumberOfLines();
                worker.ReportProgress(0, "Lines counted. Total number of lines is: " + count);
                worker.RunWorkerAsync(count);
                OutPutWindow.Text = "Document gelezen en ampersands vervangen.";
            }
        }

        private int ReadNumberOfLines()
        {
            int count = 0;
            using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (BufferedStream bs = new BufferedStream(fs))
            using (StreamReader sr = new StreamReader(bs))
                while (!sr.EndOfStream)
                {
                    sr.ReadLine();
                    count++;
                }
            return count;
        }

        private void ReplaceAmpersandAsync(object sender, DoWorkEventArgs e)
        {
            int i = 0;
            int count = (int)e.Argument;
            xmlfilename = filename + ".xml";
            StreamWriter writer = new StreamWriter(xmlfilename);
            using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (BufferedStream bs = new BufferedStream(fs))
            using (StreamReader sr = new StreamReader(bs))
            while (!sr.EndOfStream)
            {
                double percentage = (i++ * 100) / count;
                worker.ReportProgress((int)Math.Round(percentage, 0));
                if (i % 100000 == 0)
                {
                    worker.ReportProgress(i, "Linenumber " + i + " is now parsed");
                }
                string content = sr.ReadLine();
                writer.WriteLine(content.Replace("&", "&amp;"));
            }

            writer.Close();
            worker.ReportProgress(i, "All lines are parsed, file is saved");
        }

        private void ProBarChanged(object sender, ProgressChangedEventArgs e)
        {
            ProBar.Value = e.ProgressPercentage;
            OutPutWindow.Text += (string)e.UserState;
        }

        private void ReplaceAmpersandCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
        }
    }
}
1
  • Add a Debug.WriteLine() to double-check what the % complete values are being sent as. I'm not sure about the calculations. Mar 19, 2013 at 16:08

1 Answer 1

3

You are also raising too many events. You should not raise an event for every single line that is parsed. This will fill the windows message queue and it won't be able to keep up. Only raise an event each time you have some significant progress (e.g. raise an event every 1% complete).

Also the first argument to ReportProgress is supposed to be a percentage between 0 and 100 representing how complete the work is. You are misusing it here to return a line number:

worker.ReportProgress(i, "Linenumber " + i + " is now parsed");

And it's also worth mentioning that you are currently swallowing any exceptions that your code may generate. In the completed event handler you should check if there was an error:

private void ReplaceAmpersandCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Error != null) {
        // Show the user an error message.
    }
}
5
  • 2
    Also use (i * 100.0 / totalNumberOfLines) to force a double division (otherwise it will always return 0) Mar 19, 2013 at 16:09
  • I did use that statement: double percentage = (i++ * 100.0) / count; worker.ReportProgress((int)Math.Round(percentage, 0)); Mar 19, 2013 at 16:16
  • @MartijnBurger You used 100, not 100.0. The difference is significant. The first uses integer division, so the result is truncated. The second is a double, so it performs floating point division. You want the latter.
    – Servy
    Mar 19, 2013 at 16:17
  • Thanks Servy, makes sense, I adjusted it. However, the window still freezes. :( Mar 19, 2013 at 16:22
  • Integer division is fine in this case. "i * 100 / totalNumberOfLines" is correct.
    – IngisKahn
    Mar 19, 2013 at 16:24

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.