Posted By

rengber on 07/27/08


Tagged

WinForms Multithreading Asynchronous


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

umang_nine


Using a BackgroundWorker Object from a Winform


 / Published in: C#
 

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

  1. int totalLines = 0;
  2. int goodLines = 0;
  3. int badLines = 0;
  4. int colNum = 0;
  5. long bytesProcessed = 0;
  6. long fileSize = 0;
  7. string regEx = string.Empty;
  8. char[] delimiter = null;
  9. StringBuilder sb = new StringBuilder();
  10. StreamReader sr = null;
  11.  
  12. private void txtParse_Click(object sender, EventArgs e)
  13. {
  14. totalLines = 0;
  15. goodLines = 0;
  16. badLines = 0;
  17. sb = new StringBuilder();
  18.  
  19. bytesProcessed = 0;
  20. progressBar1.Value = 0;
  21. FileInfo fi = new FileInfo(txtInputFile.Text);
  22. fileSize = fi.Length;
  23.  
  24. sr = new StreamReader(txtInputFile.Text);
  25. colNum = Convert.ToInt32(txtColNum.Text);
  26. regEx = txtRegex.Text;
  27. delimiter = txtDelimiter.Text.ToCharArray();
  28.  
  29. timer1.Start();
  30. backgroundWorker1.RunWorkerAsync();
  31. }
  32.  
  33. private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
  34. {
  35. while(!sr.EndOfStream)
  36. {
  37. string rawLine = sr.ReadLine();
  38. totalLines++;
  39. bytesProcessed += rawLine.Length;
  40. string[] splitLine = rawLine.Split(delimiter);
  41. if (Regex.IsMatch(splitLine[colNum], regEx))
  42. {
  43. goodLines++;
  44. }
  45. else
  46. {
  47. badLines++;
  48. sb.AppendLine(rawLine);
  49. }
  50. }
  51. }
  52.  
  53. private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  54. {
  55. txtOutput.Text = "Lines Processed: " + totalLines.ToString() + "
  56. ";
  57. txtOutput.Text += "Good Lines: " + goodLines.ToString() + "
  58. ";
  59. txtOutput.Text += "Bad Lines: " + badLines.ToString() + "
  60. ";
  61. txtOutput.Text += sb.ToString();
  62. timer1.Stop();
  63. progressBar1.Value = 100;
  64. }
  65.  
  66. private void timer1_Tick(object sender, EventArgs e)
  67. {
  68. double ratio = Convert.ToDouble(bytesProcessed) / Convert.ToDouble(fileSize);
  69. double rawPercent = ratio * 100;
  70. int send = Convert.ToInt32(rawPercent);
  71. progressBar1.Value = send;
  72. }

Report this snippet  

You need to login to post a comment.