Return to Snippet

Revision: 7507
at July 27, 2008 23:18 by rengber


Initial Code
int totalLines = 0;
        int goodLines = 0;
        int badLines = 0;
        int colNum = 0; 
        long bytesProcessed = 0;
        long fileSize = 0;
        string regEx = string.Empty;
        char[] delimiter = null; 
        StringBuilder sb = new StringBuilder();
        StreamReader sr = null; 

        private void txtParse_Click(object sender, EventArgs e)
        {
            totalLines = 0;
            goodLines = 0;
            badLines = 0;
            sb = new StringBuilder();
            
            bytesProcessed = 0;
            progressBar1.Value = 0;
            FileInfo fi = new FileInfo(txtInputFile.Text);
            fileSize = fi.Length;
            
            sr = new StreamReader(txtInputFile.Text);
            colNum = Convert.ToInt32(txtColNum.Text);
            regEx = txtRegex.Text;
            delimiter = txtDelimiter.Text.ToCharArray();
            
            timer1.Start(); 
            backgroundWorker1.RunWorkerAsync(); 
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            while(!sr.EndOfStream)
            {
                string rawLine = sr.ReadLine();
                totalLines++;
                bytesProcessed += rawLine.Length;
                string[] splitLine = rawLine.Split(delimiter);
                if (Regex.IsMatch(splitLine[colNum], regEx))
                {
                    goodLines++;
                }
                else
                {
                    badLines++;
                    sb.AppendLine(rawLine);
                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            txtOutput.Text = "Lines Processed: " + totalLines.ToString() + "
";
            txtOutput.Text += "Good Lines: " + goodLines.ToString() + "
";
            txtOutput.Text += "Bad Lines: " + badLines.ToString() + "
";
            txtOutput.Text += sb.ToString();
            timer1.Stop();
            progressBar1.Value = 100; 
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            double ratio = Convert.ToDouble(bytesProcessed) / Convert.ToDouble(fileSize);
            double rawPercent = ratio * 100;
            int send = Convert.ToInt32(rawPercent);
            progressBar1.Value = send; 
        }

Initial URL

                                

Initial Description
I didn't like the way ReportProgress events backed up, so I ran a Timer object to update the progress meter instead.

Initial Title
Using a BackgroundWorker Object from a Winform

Initial Tags

                                

Initial Language
C#