异步操作——BackgroundWorker

作者:追风剑情 发布于:2015-10-21 18:09 分类:C#

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Threading;
  10.  
  11. namespace BackGroundWorkerTest
  12. {
  13. public partial class Form1 : Form
  14. {
  15. BackgroundWorker backgroundWorker1 = new BackgroundWorker();
  16.  
  17. public Form1()
  18. {
  19. InitializeComponent();
  20.  
  21. progressBar1.Minimum = 0;
  22. progressBar1.Maximum = 100;
  23.  
  24. backgroundWorker1.WorkerReportsProgress = true;
  25. backgroundWorker1.WorkerSupportsCancellation = true;
  26. backgroundWorker1.RunWorkerCompleted += RunWorkerCompleted;
  27. backgroundWorker1.ProgressChanged += ProgressChanged;
  28. backgroundWorker1.DoWork += DoWork;
  29. }
  30.  
  31. private void button_start_Click(object sender, EventArgs e)
  32. {
  33. if(backgroundWorker1.IsBusy)
  34. return;
  35. backgroundWorker1.RunWorkerAsync();
  36. }
  37.  
  38. private void button_cancel_Click(object sender, EventArgs e)
  39. {
  40. backgroundWorker1.CancelAsync();
  41. }
  42.  
  43. private void DoWork(object sender, DoWorkEventArgs e)
  44. {
  45. //模拟加载
  46. for (int i = 1; i <= 100; i++)
  47. {
  48. Thread.Sleep(100);
  49. //如果用户取消了操作
  50. if (backgroundWorker1.CancellationPending)
  51. {
  52. e.Cancel = true;
  53. return;
  54. }
  55.  
  56. backgroundWorker1.ReportProgress(i);
  57. }
  58. }
  59.  
  60. private void ProgressChanged(object sender, ProgressChangedEventArgs e)
  61. {
  62. progressBar1.Value = e.ProgressPercentage;//显示进度
  63. label_per.Text = e.ProgressPercentage + "%";
  64. }
  65.  
  66. private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  67. {
  68. if (e.Cancelled)
  69. {
  70. MessageBox.Show("操作被取消");
  71. }
  72. else
  73. {
  74. MessageBox.Show("操作完成");
  75. }
  76. }
  77. }
  78. }

运行效果

BBBBB.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号