using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace Backgroundworkerdemo
{
public partial class Form1 : Form
{
/// <summary>
/// 本实例演示如何在关闭窗体的时候取消Backgroundworker中正在运行的任务
/// </summary>
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
} void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine("Completed");
this.Close();//throw new NotImplementedException();
}
protected override void OnClosing(CancelEventArgs e)
{
backgroundWorker1.CancelAsync();
//如果还有任务在处理,取消关闭窗口,在任务处理完毕后再关闭
if (backgroundWorker1.IsBusy)
{
e.Cancel = true;
}
else
base.OnClosing(e);
}
private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
} void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//检查是否已经发起取消操作
while (!backgroundWorker1.CancellationPending)
{
Thread.Sleep(1000);
Console.WriteLine(DateTime.Now);
}
//throw new NotImplementedException();
} private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

  

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; using System.Xml;
using System.Threading; namespace BackgroundWorkerDownload
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent(); backgroundWorker1.DoWork += BackgroundWorker1_DoWork;
backgroundWorker1.RunWorkerCompleted += BackgroundWorker1_RunWorkerCompleted;
} private XmlDocument document = null; private void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Set progress bar to 100% in case it's not already there.
progressBar1.Value = 100; if (e.Error == null)
{
MessageBox.Show(document.InnerXml, "下載完成");
}
else
{
MessageBox.Show("無法下載檔案,下載失敗", "下載檔案", MessageBoxButtons.OK, MessageBoxIcon.Error);
} // Enable the download button and reset the progress bar.
btnDownload.Enabled = true;
progressBar1.Value = 0;
} private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
document = new XmlDocument(); Thread.Sleep(10000); // Replace this file name with a valid file name.
document.Load(@"http://www.tailspintoys.com/sample.xml");
} private void Form1_Load(object sender, EventArgs e)
{ } private void btnDownload_Click(object sender, EventArgs e)
{
// Start the download operation in the background.
backgroundWorker1.RunWorkerAsync(); // Disable the button for the duration of the download.
btnDownload.Enabled = false; // Once you have started the background thread you
// can exit the handler and the application will
// wait until the RunWorkerCompleted event is raised. // Or if you want to do something else in the main thread,
// such as update a progress bar, you can do so in a loop
// while checking IsBusy to see if the background task is
// still running.
while (this.backgroundWorker1.IsBusy)
{
progressBar1.Increment(1);
// Keep UI messages moving, so the form remains
// responsive during the asynchronous operation.
Application.DoEvents();
// 避免 CPU 飆高
Thread.Sleep(1);
}
}
}
}

  

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; using System.Threading; namespace BackgroundWorkerSimple
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
} private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.DoWork += BackgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += BackgroundWorker1_ProgressChanged;
backgroundWorker1.RunWorkerCompleted += BackgroundWorker1_RunWorkerCompleted;
} private void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
lblResult.Text = "取消";
else if (e.Error != null)
lblResult.Text = "錯誤訊息: " + e.Error.Message;
else
lblResult.Text = "完成";
} private void BackgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
lblResult.Text = $"已完成進度:{e.ProgressPercentage}%";
} private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker; for (int i = 1; i <= 10; i++)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
} // Perform a time consuming operation and report progress.
Thread.Sleep(500);
worker.ReportProgress(i * 10);
}
} private void btnStartAsync_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy == true) return;
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync();
} private void btnCancelAsync_Click(object sender, EventArgs e)
{
// WorkerSupportsCancellation 屬性為 true,才可以執行 CancelAsync method
if (backgroundWorker1.WorkerSupportsCancellation == false) return;
// Cancel the asynchronous operation.
backgroundWorker1.CancelAsync();
}
}
}

  

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; using System.IO; namespace WalkthroughBackgroundWorker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// 屬性設定
// 使用 ReportProgress() 必須把 WorkerReportsProgress 設為 true
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true; // 事件註冊
backgroundWorker1.RunWorkerCompleted += BackgroundWorker1_RunWorkerCompleted;
backgroundWorker1.ProgressChanged += BackgroundWorker1_ProgressChanged;
backgroundWorker1.DoWork += BackgroundWorker1_DoWork; txtSourceFile.Text = @"D:\Sample.txt";
txtCompareString.Text = "21934";
CounterReset();
ButtonControl(true);
}
private void StartThread()
{
CounterReset(); Words WC = new Words();
WC.SourceFile = txtSourceFile.Text.Trim();
WC.CompareString = txtCompareString.Text.Trim(); // RunWorkerAsync() 會觸發 DoWork Event
backgroundWorker1.RunWorkerAsync(WC);
}
private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// This event handler is where the actual work is done.
// This method runs on the background thread.
BackgroundWorker worker = (BackgroundWorker)sender;
Words WC = (Words)e.Argument;
WC.CountWords(worker, e);
}
private void BackgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// This method runs on the main thread.
// 更新統計資訊
Words.CurrentState state =
(Words.CurrentState)e.UserState;
txtLinesCounted.Text = state.LinesCounted.ToString();
txtWordsCounted.Text = state.WordsMatched.ToString();
}
private void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// This event handler is called when the background thread finishes.
// This method runs on the main thread.
if (e.Error != null)
MessageBox.Show("錯誤訊息:" + e.Error.Message);
else if (e.Cancelled)
MessageBox.Show("字數統計取消");
else
MessageBox.Show("完成字數統計"); ButtonControl(true);
}
private void btnStart_Click(object sender, EventArgs e)
{
if (File.Exists(txtSourceFile.Text.Trim()) == false)
{
MessageBox.Show("該檔案路徑不存在,無法進行解析", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
} ButtonControl(false);
StartThread();
}
private void btnCancel_Click(object sender, EventArgs e)
{
// 取消非同步操作
backgroundWorker1.CancelAsync();
CounterReset();
ButtonControl(true);
}
private void ButtonControl(bool state)
{
btnStart.Enabled = state;
btnCancel.Enabled = !state;
}
private void CounterReset()
{
txtWordsCounted.Text = "0";
txtLinesCounted.Text = "0";
}
private void btnFileSelect_Click(object sender, EventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();
fd.Filter = "txt 檔案 (*.*)|*.txt";
fd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (fd.ShowDialog() == DialogResult.Cancel) return;
txtSourceFile.Text = fd.FileName;
}
}
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Text.RegularExpressions;
using System.ComponentModel;
using System.IO;
using System.Threading; namespace WalkthroughBackgroundWorker
{
public class Words
{
// Object to store the current state, for passing to the caller.
public class CurrentState
{
public int LinesCounted { get; set; }
public int WordsMatched { get; set; }
} public string SourceFile { get; set; }
public string CompareString { get; set; }
private int WordCount { get; set; }
private int LinesCounted { get; set; } public void CountWords(BackgroundWorker worker, DoWorkEventArgs e)
{
if (string.IsNullOrEmpty(CompareString))
throw new Exception("沒有指定搜尋字串"); // 變數初始化
CurrentState state = new CurrentState();
string line = string.Empty;
// int elapsedTime = 20;
// DateTime lastReportDateTime = DateTime.Now; // 利用 StreamReader 讀取 txt 檔案
using (StreamReader sr = new StreamReader(SourceFile))
{
// Process lines while there are lines remaining in the file.
while (!sr.EndOfStream)
{
// 使用者取消後,就不繼續讀取
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
} line = sr.ReadLine();
WordCount += CountInString(line, CompareString);
// 紀錄行數
LinesCounted++; // Raise an event so the form can monitor progress.
// 每 20 毫秒才透過 ReportProgress() 觸發 ProgressChanged Event,避免觸發太過頻繁
//int compare = DateTime.Compare(
// DateTime.Now,
// lastReportDateTime.AddMilliseconds(elapsedTime));
//if (compare < 0) continue; state.LinesCounted = LinesCounted;
state.WordsMatched = WordCount;
worker.ReportProgress(0, state);
// 重置 lastReportDateTime 變數
// lastReportDateTime = DateTime.Now;
// 處理每一行都停止 50 毫秒,方便觀察執行結果
Thread.Sleep(50);
} // Report the final count values.
state.LinesCounted = LinesCounted;
state.WordsMatched = WordCount;
worker.ReportProgress(100, state);
}
} private int CountInString(string SourceString, string CompareString)
{
// This function counts the number of times
// a word is found in a line.
if (SourceString == null)
{
return 0;
} // Regex.Escape:以逸出碼取代 (\、*、+、?、|、{、[、(、)、^、$、.、# 和泛空白字元) 等字元。 這樣會指示規則運算式引擎將這些字元解譯為常值,而非解譯為中繼字元。
string EscapedCompareString = Regex.Escape(CompareString); // To count all occurrences of the string, even within words, remove both instances of @"\b" from the following line.
// 下述兩種寫法都可以使用
string pattern = @"\b" + EscapedCompareString + @"\b";
// string pattern = $"\\b{EscapedCompareString}\\b"; Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(SourceString);
return matches.Count;
}
}
}

  

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. 云栖PPT下载 | 开源界大咖集体现身,开源数据库专场重点再回眸!

    阿里云开源数据库项目最新发布 阿里巴巴集团副总裁.阿里云智能数据库事业部总裁.高级研究员李飞飞(飞刀).阿里云数据库资深技术专家楼方鑫(黄忠)以及阿里云数据库技术专家傅宇(齐木)三位阿里云技术专家为大 ...

  2. 远程仓库 GitHub

    远程仓库 这里介绍的远程仓库指的是 GitHub, 在这个网站,所有非私有的的代码,都可以被其他人查看,所以,一些机密或者重要的文件千万不要上传到这里面,如果需要可以购买付费版本或自己公司搭建埃及的远 ...

  3. PHP ftp_get_option() 函数

    定义和用法 The ftp_get_option() 函数返回 FTP 连接的各种运行时选项. 语法 ftp_get_option(ftp_connection,option) 参数 描述 ftp_c ...

  4. 管理员技术(二): 访问练习用虚拟机、 命令行基础技巧 、 挂载并访问光盘设备、ls列表及文档创建、复制删除移动

    一.访问练习用虚拟机 目标: 学会在教学环境中访问练习用虚拟机,主要完成以下事项: 1> 快速重置教学虚拟机环境       2> 通过“虚拟系统管理器”访问虚拟机       3> ...

  5. 出现Warning: date(): It is not safe to rely on the system's timezone settings的解决办法

    在没有配置,尤其是新安装的PHP中使用date函数时,会报这个错误: Warning: date(): It is not safe to rely on the system's timezone ...

  6. VS2012编译WDM驱动

    新版的VS2012中集成了WDK8,而且WDK8中已经没有之前的Build Environment了,看来编译驱动只能通过VS2012了,直接开发WDF驱动很方便直接选取相应的模板即可,若是编译以前的 ...

  7. __iomem作用

    最近在看网卡驱动时查看ioremap函数发现调用最低层用__iomem修饰了ioremap的第一个参数(unsigned int)ioremap(S3C24XX_PA_CS8900, SZ_1M) + ...

  8. PHP面试 PHP基础知识 二(常量及数据类型)

    常量及数据类型 PHP八种数据类型 四种标量类型 字符串(string).布尔(boolean).浮点(float/double).整型(integer) 两种复合类型 数组(array).对象(ob ...

  9. SVN工作副本已经锁定错误的解决方法

    SVN工作副本锁定错误的解决方法 我们在使用svn版本控制软件时,时常会遇到想要更新本地项目的版本,却突然提示:工作副本已锁定.截图如下: 这种错误让人感觉很不舒服,实际上自己也没做过什么操作就这样了 ...

  10. 3、第一个Appium测试

    运行脚本前环境准备: 1.IDE,推荐使用IJ 2.安装jdk环境,推荐>1.8 3.准备一台真机或者模拟器 4.SDK 5.maven环境 项目目录: CalculatorTest.java文 ...