编辑
2025-09-29
C#
00

BackgroundWorker

image.png

C#
using System.ComponentModel; namespace threadexp { public partial class FrmMain : Form { //实例化BackgroundWorker private BackgroundWorker bgWorker = new BackgroundWorker(); public FrmMain() { InitializeComponent(); } private void FrmMain_Load(object sender, EventArgs e) { pbar.Maximum = 1000; //是否报告处理进度 bgWorker.WorkerReportsProgress = true; //是否允许取消操作 bgWorker.WorkerSupportsCancellation = true; //执行三个事件,DoWork事件,ProgressChanged事件以及RunWorkedCompleted事件 bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork); bgWorker.ProgressChanged += new ProgressChangedEventHandler(bgWorker_ProgessChanged); bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_WorkerCompleted); } public void bgWorker_DoWork(object sender, DoWorkEventArgs e) { //设置进度条Maximum为1000,循环1000次 for (int i = 0; i <= 1000; i++) { //获取是否取消操作 if (bgWorker.CancellationPending) { e.Cancel = true; return; } else { //报告进度 bgWorker.ReportProgress(i, "Working"); System.Threading.Thread.Sleep(10); } } } public void bgWorker_ProgessChanged(object sender, ProgressChangedEventArgs e) { //e.ProgressPercentage是获取任务int类型 pbar.Value = e.ProgressPercentage; lblTitle.Text = "处理进度:" + Convert.ToString(e.ProgressPercentage); } public void bgWorker_WorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //若没有完全执行结束,则报错 if (e.Error != null) { MessageBox.Show(e.Error.ToString()); return; } if (!e.Cancelled) this.lblTitle.Text = "处理完毕!"; else this.lblTitle.Text = "处理终止!"; } //开始 private void btnStart_Click(object sender, EventArgs e) { //正忙时不允许继续操作 if (bgWorker.IsBusy) return; //异步开启 bgWorker.RunWorkerAsync("start"); } //停止 private void btnStop_Click(object sender, EventArgs e) { bgWorker.CancelAsync(); } } }

image.png

C#
namespace threadexp1 { public partial class FrmMain : Form { Thread thread; public FrmMain() { InitializeComponent(); //这个不推荐使用 //Control.CheckForIllegalCrossThreadCalls = false; } private void btnCal_Click(object sender, EventArgs e) { thread = new Thread(CalValue); thread.Start(); } private void CalValue() { for (int i = 0; i < 300000; i++) { this.Invoke(new Action(() => { this.txtValue.Text = i.ToString(); })); } } private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) { if (thread != null) { //thread.Abort();//这个在.net core中会出错 } } } }

参数传递

使用object

C#
private void btnStart_Click(object sender, EventArgs e) { Thread thread = new Thread(new ParameterizedThreadStart(Cal)); thread.Start(100);//传参数 } private void Cal(object o) { for (int i = int.Parse(o.ToString()); i < 100000; i++) { this.Invoke(() => { txtValue.Text = i.ToString(); }); } }

使用类

C#
internal class CCal { private int data; private System.Windows.Forms.TextBox txt; public CCal(int data, System.Windows.Forms.TextBox txt) { this.data = data; this.txt = txt; } public void SetValue() { for (int i = data; i < 100000; i++) { txt.Invoke(() => { txt.Text = i.ToString(); }); } } }
C#
CCal cal = new CCal(1000,this.txtValue); Thread thread = new Thread(cal.SetValue); thread.Start();

使用lambada表达式

C#
private void btnStart_Click(object sender, EventArgs e) { Thread thread = new Thread(() => Cal(100)); thread.Start(); } private void Cal(int data) { for (int i = data; i < 100000; i++) { this.Invoke(() => { txtValue.Text = i.ToString(); }); } }

Task

image.png

C#
public partial class FrmMain : Form { CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct; public FrmMain() { InitializeComponent(); this.pbar.Maximum = 1000; } private void btnStart_Click(object sender, EventArgs e) { ct = cts.Token; Task.Run(() => { Do(); }, ct); } private void btnStop_Click(object sender, EventArgs e) { cts.Cancel(); } private void Do() { for (int i = 1; i <= 1000; i++) { if (!ct.IsCancellationRequested) { this.Invoke(new Action(() => { this.pbar.Value++; lblTitle.Text = i.ToString(); })); System.Threading.Thread.Sleep(10); } } } }

image.png

C#
public partial class FrmMain : Form { CancellationTokenSource _cancelSource = new CancellationTokenSource(); CancellationToken _cancelToken; ManualResetEvent _resetEvent = new ManualResetEvent(true); public FrmMain() { InitializeComponent(); this.pbar.Maximum = 1000; } private void btnStart_Click(object sender, EventArgs e) { pbar.Value = 0; //任务取消后如果想重开任务,不能使用已经取消的token,需要重新声明一个对象. _cancelSource = new CancellationTokenSource(); _cancelToken = _cancelSource.Token; Task.Run(() => { Do(); }, _cancelToken); } private void Do() { for (int i = 1; i <= 1000; i++) { if (_cancelToken.IsCancellationRequested) { return; } //初始化为true时执行WaitOne不阻塞 _resetEvent.WaitOne(); this.Invoke(new Action(() => { this.pbar.Value++; lblTitle.Text = i.ToString(); })); System.Threading.Thread.Sleep(10); } } private void btnStop_Click(object sender, EventArgs e) { //暂停Task _resetEvent.Reset(); } private void btnContinue_Click(object sender, EventArgs e) { //继续Task _resetEvent.Set(); } private void btnCancel_Click(object sender, EventArgs e) { //取消Task _cancelSource.Cancel(); } }

异步方法(async/await)

image.png

C#
private async void btnCal_Click(object sender, EventArgs e) { int sum = await Sum(100); txtValue.Text = sum.ToString(); } async Task<int> Sum(int value) { var sum = 0; for (int i = value; i < 10000; i++) { sum += i; } return sum; }

System.Timer

image.png

C#
public partial class FrmMain : Form { System.Timers.Timer timer = new System.Timers.Timer(); public FrmMain() { InitializeComponent(); timer.Interval = 100; timer.Elapsed += Timer_Elapsed; } private void Timer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e) { Random random = new Random(); int idx = random.Next(0, flowLayoutPanel1.Controls.Count); this.Invoke(() => { ((Label)(flowLayoutPanel1.Controls[idx])).BackColor = Color.DarkRed; Thread.Sleep(10); }); } private void btnDraw_Click(object sender, EventArgs e) { flowLayoutPanel1.AutoScroll = true; for (int i = 0; i < 100; i++) { Label lbl = new Label(); lbl.Text = i.ToString(); lbl.BackColor = Color.Blue; lbl.BorderStyle = BorderStyle.Fixed3D; lbl.ForeColor = Color.Wheat; flowLayoutPanel1.Controls.Add(lbl); } } private void btnModify_Click(object sender, EventArgs e) { timer.Start(); } }

Parallel

image.png

C#
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnRun_Click(object sender, EventArgs e) { var actions = new Action[]{ () => ActionTest(1), () => ActionTest(2), () => ActionTest(3), () => ActionTest(4) }; ThreadPool.QueueUserWorkItem(w => { Parallel.ForEach(actions, it => { it(); }); }); } void Sum() { int sum = 0; for (int i = 1; i <= 1000; i++) { sum += i; this.BeginInvoke(new Action(() => { ((TextBox)this.Controls["txt1"]).Text = sum.ToString(); })); System.Threading.Thread.Sleep(10); } } void ActionTest(object value) { int sum = 0; for (int i = int.Parse(value.ToString()); i < 1000; i++) { sum += i; this.Invoke(() => { ((TextBox)this.Controls["txt" + value.ToString()]).Text = sum.ToString(); }); Thread.Sleep(10); } } }

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!