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.Threading; namespace WindowsFormsApplication3 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public struct CalcInput { public int x; public int y; public CalcInput(int x,int y) { this.x = x; this.y = y; } } private void OnCalculate(object sender, EventArgs e) { this.buttonCalculate.Enabled = false; this.textBoxResult.Text = string.Empty; this.buttonCancel.Enabled = true; this.progressBar.Value = 0; this.backgroundWorker1.RunWorkerAsync(new CalcInput(int.Parse(this.textBox.Text),int.Parse(this.textBoxY.Text))); } private void OnDoWork(object sender, DoWorkEventArgs e) { CalcInput input = (CalcInput)e.Argument; //Thread.Sleep(5000); for(int i=0;i<10;i++) { Thread.Sleep(5000); backgroundWorker1.ReportProgress(i*10); if(backgroundWorker1.CancellationPending) { e.Cancel = true; return; } } e.Result = input.x + input.y; } private void OnWorkCompleted(object sender, RunWorkerCompletedEventArgs e) { if(e.Cancelled) { this.textBoxResult.Text = "Cancelled"; } else { this.textBoxResult.Text = e.Result.ToString(); } //this.textBoxResult.Text = e.Result.ToString(); this.buttonCalculate.Enabled = true; this.buttonCancel.Enabled = false; //for (int i = 0; i <= 100;i++ ) //{ // this.progressBar.Value++; //} this.progressBar.Value = 100; } private void OnCancel(object sender, EventArgs e) { backgroundWorker1.CancelAsync(); } private void OnPorgressChanged(object sender, ProgressChangedEventArgs e) { this.progressBar.Value = e.ProgressPercentage; } } }