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.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.Threading;
  11. namespace Backgroundworkerdemo
  12. {
  13. public partial class Form1 : Form
  14. {
  15. /// <summary>
  16. /// 本实例演示如何在关闭窗体的时候取消Backgroundworker中正在运行的任务
  17. /// </summary>
  18. public Form1()
  19. {
  20. InitializeComponent();
  21. backgroundWorker1.WorkerSupportsCancellation = true;
  22. backgroundWorker1.DoWork += backgroundWorker1_DoWork;
  23. backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
  24. }
  25.  
  26. void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  27. {
  28. Console.WriteLine("Completed");
  29. this.Close();//throw new NotImplementedException();
  30. }
  31. protected override void OnClosing(CancelEventArgs e)
  32. {
  33. backgroundWorker1.CancelAsync();
  34. //如果还有任务在处理,取消关闭窗口,在任务处理完毕后再关闭
  35. if (backgroundWorker1.IsBusy)
  36. {
  37. e.Cancel = true;
  38. }
  39. else
  40. base.OnClosing(e);
  41. }
  42. private void Form1_Load(object sender, EventArgs e)
  43. {
  44. backgroundWorker1.RunWorkerAsync();
  45. }
  46.  
  47. void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
  48. {
  49. //检查是否已经发起取消操作
  50. while (!backgroundWorker1.CancellationPending)
  51. {
  52. Thread.Sleep(1000);
  53. Console.WriteLine(DateTime.Now);
  54. }
  55. //throw new NotImplementedException();
  56. }
  57.  
  58. private void button1_Click(object sender, EventArgs e)
  59. {
  60. this.Close();
  61. }
  62. }
  63. }

  

  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.  
  10. using System.Xml;
  11. using System.Threading;
  12.  
  13. namespace BackgroundWorkerDownload
  14. {
  15. public partial class Form1 : Form
  16. {
  17. public Form1()
  18. {
  19. InitializeComponent();
  20.  
  21. backgroundWorker1.DoWork += BackgroundWorker1_DoWork;
  22. backgroundWorker1.RunWorkerCompleted += BackgroundWorker1_RunWorkerCompleted;
  23. }
  24.  
  25. private XmlDocument document = null;
  26.  
  27. private void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  28. {
  29. // Set progress bar to 100% in case it's not already there.
  30. progressBar1.Value = 100;
  31.  
  32. if (e.Error == null)
  33. {
  34. MessageBox.Show(document.InnerXml, "下載完成");
  35. }
  36. else
  37. {
  38. MessageBox.Show("無法下載檔案,下載失敗", "下載檔案", MessageBoxButtons.OK, MessageBoxIcon.Error);
  39. }
  40.  
  41. // Enable the download button and reset the progress bar.
  42. btnDownload.Enabled = true;
  43. progressBar1.Value = 0;
  44. }
  45.  
  46. private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
  47. {
  48. document = new XmlDocument();
  49.  
  50. Thread.Sleep(10000);
  51.  
  52. // Replace this file name with a valid file name.
  53. document.Load(@"http://www.tailspintoys.com/sample.xml");
  54. }
  55.  
  56. private void Form1_Load(object sender, EventArgs e)
  57. {
  58.  
  59. }
  60.  
  61. private void btnDownload_Click(object sender, EventArgs e)
  62. {
  63. // Start the download operation in the background.
  64. backgroundWorker1.RunWorkerAsync();
  65.  
  66. // Disable the button for the duration of the download.
  67. btnDownload.Enabled = false;
  68.  
  69. // Once you have started the background thread you
  70. // can exit the handler and the application will
  71. // wait until the RunWorkerCompleted event is raised.
  72.  
  73. // Or if you want to do something else in the main thread,
  74. // such as update a progress bar, you can do so in a loop
  75. // while checking IsBusy to see if the background task is
  76. // still running.
  77. while (this.backgroundWorker1.IsBusy)
  78. {
  79. progressBar1.Increment(1);
  80. // Keep UI messages moving, so the form remains
  81. // responsive during the asynchronous operation.
  82. Application.DoEvents();
  83. // 避免 CPU 飆高
  84. Thread.Sleep(1);
  85. }
  86. }
  87. }
  88. }

  

  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.Threading.Tasks;
  9. using System.Windows.Forms;
  10.  
  11. using System.Threading;
  12.  
  13. namespace BackgroundWorkerSimple
  14. {
  15. public partial class Form1 : Form
  16. {
  17. public Form1()
  18. {
  19. InitializeComponent();
  20. backgroundWorker1.WorkerReportsProgress = true;
  21. backgroundWorker1.WorkerSupportsCancellation = true;
  22. }
  23.  
  24. private void Form1_Load(object sender, EventArgs e)
  25. {
  26. backgroundWorker1.DoWork += BackgroundWorker1_DoWork;
  27. backgroundWorker1.ProgressChanged += BackgroundWorker1_ProgressChanged;
  28. backgroundWorker1.RunWorkerCompleted += BackgroundWorker1_RunWorkerCompleted;
  29. }
  30.  
  31. private void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  32. {
  33. if (e.Cancelled == true)
  34. lblResult.Text = "取消";
  35. else if (e.Error != null)
  36. lblResult.Text = "錯誤訊息: " + e.Error.Message;
  37. else
  38. lblResult.Text = "完成";
  39. }
  40.  
  41. private void BackgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
  42. {
  43. lblResult.Text = $"已完成進度:{e.ProgressPercentage}%";
  44. }
  45.  
  46. private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
  47. {
  48. BackgroundWorker worker = sender as BackgroundWorker;
  49.  
  50. for (int i = 1; i <= 10; i++)
  51. {
  52. if (worker.CancellationPending == true)
  53. {
  54. e.Cancel = true;
  55. break;
  56. }
  57.  
  58. // Perform a time consuming operation and report progress.
  59. Thread.Sleep(500);
  60. worker.ReportProgress(i * 10);
  61. }
  62. }
  63.  
  64. private void btnStartAsync_Click(object sender, EventArgs e)
  65. {
  66. if (backgroundWorker1.IsBusy == true) return;
  67. // Start the asynchronous operation.
  68. backgroundWorker1.RunWorkerAsync();
  69. }
  70.  
  71. private void btnCancelAsync_Click(object sender, EventArgs e)
  72. {
  73. // WorkerSupportsCancellation 屬性為 true,才可以執行 CancelAsync method
  74. if (backgroundWorker1.WorkerSupportsCancellation == false) return;
  75. // Cancel the asynchronous operation.
  76. backgroundWorker1.CancelAsync();
  77. }
  78. }
  79. }

  

  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.Threading.Tasks;
  9. using System.Windows.Forms;
  10.  
  11. using System.IO;
  12.  
  13. namespace WalkthroughBackgroundWorker
  14. {
  15. public partial class Form1 : Form
  16. {
  17. public Form1()
  18. {
  19. InitializeComponent();
  20. }
  21. private void Form1_Load(object sender, EventArgs e)
  22. {
  23. // 屬性設定
  24. // 使用 ReportProgress() 必須把 WorkerReportsProgress 設為 true
  25. backgroundWorker1.WorkerReportsProgress = true;
  26. backgroundWorker1.WorkerSupportsCancellation = true;
  27.  
  28. // 事件註冊
  29. backgroundWorker1.RunWorkerCompleted += BackgroundWorker1_RunWorkerCompleted;
  30. backgroundWorker1.ProgressChanged += BackgroundWorker1_ProgressChanged;
  31. backgroundWorker1.DoWork += BackgroundWorker1_DoWork;
  32.  
  33. txtSourceFile.Text = @"D:\Sample.txt";
  34. txtCompareString.Text = "21934";
  35. CounterReset();
  36. ButtonControl(true);
  37. }
  38. private void StartThread()
  39. {
  40. CounterReset();
  41.  
  42. Words WC = new Words();
  43. WC.SourceFile = txtSourceFile.Text.Trim();
  44. WC.CompareString = txtCompareString.Text.Trim();
  45.  
  46. // RunWorkerAsync() 會觸發 DoWork Event
  47. backgroundWorker1.RunWorkerAsync(WC);
  48. }
  49. private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
  50. {
  51. // This event handler is where the actual work is done.
  52. // This method runs on the background thread.
  53. BackgroundWorker worker = (BackgroundWorker)sender;
  54. Words WC = (Words)e.Argument;
  55. WC.CountWords(worker, e);
  56. }
  57. private void BackgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
  58. {
  59. // This method runs on the main thread.
  60. // 更新統計資訊
  61. Words.CurrentState state =
  62. (Words.CurrentState)e.UserState;
  63. txtLinesCounted.Text = state.LinesCounted.ToString();
  64. txtWordsCounted.Text = state.WordsMatched.ToString();
  65. }
  66. private void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  67. {
  68. // This event handler is called when the background thread finishes.
  69. // This method runs on the main thread.
  70. if (e.Error != null)
  71. MessageBox.Show("錯誤訊息:" + e.Error.Message);
  72. else if (e.Cancelled)
  73. MessageBox.Show("字數統計取消");
  74. else
  75. MessageBox.Show("完成字數統計");
  76.  
  77. ButtonControl(true);
  78. }
  79. private void btnStart_Click(object sender, EventArgs e)
  80. {
  81. if (File.Exists(txtSourceFile.Text.Trim()) == false)
  82. {
  83. MessageBox.Show("該檔案路徑不存在,無法進行解析", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
  84. return;
  85. }
  86.  
  87. ButtonControl(false);
  88. StartThread();
  89. }
  90. private void btnCancel_Click(object sender, EventArgs e)
  91. {
  92. // 取消非同步操作
  93. backgroundWorker1.CancelAsync();
  94. CounterReset();
  95. ButtonControl(true);
  96. }
  97. private void ButtonControl(bool state)
  98. {
  99. btnStart.Enabled = state;
  100. btnCancel.Enabled = !state;
  101. }
  102. private void CounterReset()
  103. {
  104. txtWordsCounted.Text = "0";
  105. txtLinesCounted.Text = "0";
  106. }
  107. private void btnFileSelect_Click(object sender, EventArgs e)
  108. {
  109. OpenFileDialog fd = new OpenFileDialog();
  110. fd.Filter = "txt 檔案 (*.*)|*.txt";
  111. fd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
  112. if (fd.ShowDialog() == DialogResult.Cancel) return;
  113. txtSourceFile.Text = fd.FileName;
  114. }
  115. }
  116. }

  

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. using System.Text.RegularExpressions;
  8. using System.ComponentModel;
  9. using System.IO;
  10. using System.Threading;
  11.  
  12. namespace WalkthroughBackgroundWorker
  13. {
  14. public class Words
  15. {
  16. // Object to store the current state, for passing to the caller.
  17. public class CurrentState
  18. {
  19. public int LinesCounted { get; set; }
  20. public int WordsMatched { get; set; }
  21. }
  22.  
  23. public string SourceFile { get; set; }
  24. public string CompareString { get; set; }
  25. private int WordCount { get; set; }
  26. private int LinesCounted { get; set; }
  27.  
  28. public void CountWords(BackgroundWorker worker, DoWorkEventArgs e)
  29. {
  30. if (string.IsNullOrEmpty(CompareString))
  31. throw new Exception("沒有指定搜尋字串");
  32.  
  33. // 變數初始化
  34. CurrentState state = new CurrentState();
  35. string line = string.Empty;
  36. // int elapsedTime = 20;
  37. // DateTime lastReportDateTime = DateTime.Now;
  38.  
  39. // 利用 StreamReader 讀取 txt 檔案
  40. using (StreamReader sr = new StreamReader(SourceFile))
  41. {
  42. // Process lines while there are lines remaining in the file.
  43. while (!sr.EndOfStream)
  44. {
  45. // 使用者取消後,就不繼續讀取
  46. if (worker.CancellationPending == true)
  47. {
  48. e.Cancel = true;
  49. break;
  50. }
  51.  
  52. line = sr.ReadLine();
  53. WordCount += CountInString(line, CompareString);
  54. // 紀錄行數
  55. LinesCounted++;
  56.  
  57. // Raise an event so the form can monitor progress.
  58. // 每 20 毫秒才透過 ReportProgress() 觸發 ProgressChanged Event,避免觸發太過頻繁
  59. //int compare = DateTime.Compare(
  60. // DateTime.Now,
  61. // lastReportDateTime.AddMilliseconds(elapsedTime));
  62. //if (compare < 0) continue;
  63.  
  64. state.LinesCounted = LinesCounted;
  65. state.WordsMatched = WordCount;
  66. worker.ReportProgress(0, state);
  67. // 重置 lastReportDateTime 變數
  68. // lastReportDateTime = DateTime.Now;
  69. // 處理每一行都停止 50 毫秒,方便觀察執行結果
  70. Thread.Sleep(50);
  71. }
  72.  
  73. // Report the final count values.
  74. state.LinesCounted = LinesCounted;
  75. state.WordsMatched = WordCount;
  76. worker.ReportProgress(100, state);
  77. }
  78. }
  79.  
  80. private int CountInString(string SourceString, string CompareString)
  81. {
  82. // This function counts the number of times
  83. // a word is found in a line.
  84. if (SourceString == null)
  85. {
  86. return 0;
  87. }
  88.  
  89. // Regex.Escape:以逸出碼取代 (\、*、+、?、|、{、[、(、)、^、$、.、# 和泛空白字元) 等字元。 這樣會指示規則運算式引擎將這些字元解譯為常值,而非解譯為中繼字元。
  90. string EscapedCompareString = Regex.Escape(CompareString);
  91.  
  92. // To count all occurrences of the string, even within words, remove both instances of @"\b" from the following line.
  93. // 下述兩種寫法都可以使用
  94. string pattern = @"\b" + EscapedCompareString + @"\b";
  95. // string pattern = $"\\b{EscapedCompareString}\\b";
  96.  
  97. Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
  98. MatchCollection matches = regex.Matches(SourceString);
  99. return matches.Count;
  100. }
  101. }
  102. }

  

BackgroundWorker study的更多相关文章

  1. C# BackgroundWorker 详解

    在C#程序中,经常会有一些耗时较长的CPU密集型运算,如果直接在 UI 线程执行这样的运算就会出现UI不响应的问题.解决这类问题的主要途径是使用多线程,启动一个后台线程,把运算操作放在这个后台线程中完 ...

  2. 【Winform】使用BackgroundWorker控制进度条显示进度

    许多开发者看见一些软件有进度条显示进度,自己想弄,项目建好后发现并没有自己想象中的那么简单...看了网上很多教程后,写了一个小Demo供网友们参考~~,Demo的网址:http://pan.baidu ...

  3. Improve Your Study Habits

    1.Plan your time carefully. Make a list of your weekly tasks.Then make a schedule or chart of your t ...

  4. C# 多線程&BackgroundWorker概念入門教程

    感謝以下各位作者的貢獻~ 百度經驗舉了個例子,很好理解BackgroundWorker的用途(主要是用來啟動後台線程,而不阻塞調用程式的運行),收藏一下  http://jingyan.baidu.c ...

  5. 【C#】【Thread】BackgroundWorker的使用

    BackgroundWorker 可以用于启动后台线程. 主要的事件及参数: 1.DoWork --当执行BackgroundWorker.RunWorkerAsync方法时会触发该事件,并且传递Do ...

  6. 用于异步的BackgroundWorker

    XAML代码: <Window x:Class="backgroundtest.MainWindow" xmlns="http://schemas.microsof ...

  7. C# 使用BackgroundWorker例子及注意点

    该例子为使用BackgroundWorker在TextBox文本中产生一个10000以内并且能被5整除的数(1秒产生一个) 操作界面可以启动线程,也可以停止线程,界面设计如图: 先贴代码,有注释的地方 ...

  8. C# BackgroundWorker组件学习入门介绍

    C# BackgroundWorker组件学习入门介绍 一个程序中需要进行大量的运算,并且需要在运算过程中支持用户一定的交互,为了获得更好的用户体验,使用BackgroundWorker来完成这一功能 ...

  9. winform异步系统升级—BackgroundWorker

    BackgroundWorker用法实例 自己的代码,就是要执行的代码写到dowork里,ProgressChanged事件是控制进度时用的,最后的Completed事件进度完成,也就是dowork里 ...

随机推荐

  1. OpenSearch最新功能介绍

    摘要:阿里云开放搜索(OpenSearch)是一款结构化数据搜索托管服务,其能够提供简单.高效.稳定.低成本和可扩展的搜索解决方案.OpenSearch以平台服务化的形式,将专业搜索技术简单化.低门槛 ...

  2. spring之循环依赖问题如何解决

    首先,spring是支持循环依赖的.但是循环依赖并不好. 最近,我在使用jenkins自动化部署,测试打出来的jar包,出现了循环依赖的问题. 在这里说一下,我解决问题的过程 我首先根据提示找到循环依 ...

  3. docker组件如何协作(7)

    还记得我们运行的第一个容器吗?现在通过它来体会一下 Docker 各个组件是如何协作的. 容器启动过程如下: Docker 客户端执行 docker run 命令. Docker daemon 发现本 ...

  4. php开发面试题---1、php常用面试题一(PHP有哪些特性)

    php开发面试题---1.php常用面试题一(PHP有哪些特性) 一.总结 一句话总结: ①.混合语法:php独特混合了C,Java,Prel以及PHP自创的语法. ②.为动态网页而生:可以比CGI或 ...

  5. java程序中线程cpu使用率计算

    原文地址:https://www.imooc.com/article/27374 最近确实遇到题目上的刚需,也是花了一段时间来思考这个问题. cpu使用率如何计算 计算使用率在上学那会就经常算,不过往 ...

  6. FreeBSD_11-系统管理——{Part_a-bhyve}

    ;; 创建 vm: #!/usr/bin/env zsh bridgeIF=bridge0 laggIF=lagg0 tapIF=tap0 phyIF_0=re0 phyIF_1=em0 isoPat ...

  7. 使用SpringMVC<mvc:view-controller/>标签时踩的一个坑

    <mvc:view-controller>标签 如果我们有些请求只是想跳转页面,不需要来后台处理什么逻辑,我们无法在Action中写一个空方法来跳转,直接在中配置一个如下的视图跳转控制器即 ...

  8. 总分 Score Inflation

    题目背景 学生在我们USACO的竞赛中的得分越多我们越高兴. 我们试着设计我们的竞赛以便人们能尽可能的多得分,这需要你的帮助 题目描述 我们可以从几个种类中选取竞赛的题目,这里的一个"种类& ...

  9. 长度为x的本质不同的串的出现次数 SPOJ - NSUBSTR 后缀自动机简单应用

    题意: 长度为x的本质不同的串的出现次数 题解: 先处理出每一个节点所对应的子串出现的次数 然后取max就好了 #include <set> #include <map> #i ...

  10. UncategorizedSQLException异常处理办法

    如题,先贴console org.springframework.jdbc.UncategorizedSQLException: StatementCallback; uncategorized SQ ...