标签:threading img async windows ace 取消 mod col sync
为了确保 backgroundWorker1_ProgressChanged事件能起作用 设置 WorkerReportsProgress = True;
为了确保能取消操作 设置 WorkerSupportsCancellation = True 这样代码 backgroundWorker1.CancelAsync(); 就不会出错
using System; using System.ComponentModel; using System.Threading; using System.Windows.Forms; namespace WindowsFormsAppBackGroundWorker { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender,EventArgs e) { //start if (!backgroundWorker1.IsBusy) backgroundWorker1.RunWorkerAsync(textBox1.Text);
//此处的Object数值 存放在 DoWorkEventArgs的Argument里面
//可在 backgroundWorker1_DoWork事件的 e.Argument获取
} private void button2_Click(object sender,EventArgs e) { //stop //backgroundWorker1.WorkerSupportsCancellation = true; if (backgroundWorker1.IsBusy) backgroundWorker1.CancelAsync(); } private void backgroundWorker1_DoWork(object sender,DoWorkEventArgs e) { int length = int.Parse(textBox1.Text); progressBar1.Maximum = length; backgroundWorker1.ReportProgress(1,"Begin..."); for (int i = 0; i < length; i++) { if (!backgroundWorker1.CancellationPending) { backgroundWorker1.ReportProgress(i,i); Thread.Sleep(10); } } backgroundWorker1.ReportProgress(100,"Complete!"); } private void backgroundWorker1_ProgressChanged(object sender,ProgressChangedEventArgs e) { progressBar1.Value = unchecked(e.ProgressPercentage); label1.Text = e.UserState.ToString(); } private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e) { //Text = "RunWorkerCompleted"; } } }
标签:threading img async windows ace 取消 mod col sync
原文地址:https://www.cnblogs.com/xe2011/p/13194684.html