BackgroundWorker学习笔记
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
namespace BackgroundWorkerForm
{
public struct CalcInput
{
public CalcInput(int x, int y)
{
this.x = x;
this.y = y;
}
public int x;
public int y;
}
{
public struct CalcInput
{
public CalcInput(int x, int y)
{
this.x = x;
this.y = y;
}
public int x;
public int y;
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
{
public Form1()
{
InitializeComponent();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
CalcInput input = (CalcInput)e.Argument;
for (int i = 0; i < 100; i++)
{
Thread.Sleep(300);
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
backgroundWorker1.ReportProgress(i);
}
e.Result = input.x * input.y;
}
{
CalcInput input = (CalcInput)e.Argument;
for (int i = 0; i < 100; i++)
{
Thread.Sleep(300);
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
backgroundWorker1.ReportProgress(i);
}
e.Result = input.x * input.y;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
textBox3.Text = "Cancelled";
}
else
{
textBox3.Text = e.Result.ToString();
}
button1.Enabled = true;
button2.Enabled = false;
progressBar1.Value = 100;
}
{
if (e.Cancelled)
{
textBox3.Text = "Cancelled";
}
else
{
textBox3.Text = e.Result.ToString();
}
button1.Enabled = true;
button2.Enabled = false;
progressBar1.Value = 100;
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
button2.Enabled = true;
backgroundWorker1.RunWorkerAsync(new CalcInput(int.Parse(textBox1.Text),int.Parse(textBox2.Text)));
}
{
button1.Enabled = false;
button2.Enabled = true;
backgroundWorker1.RunWorkerAsync(new CalcInput(int.Parse(textBox1.Text),int.Parse(textBox2.Text)));
}
private void button2_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
{
backgroundWorker1.CancelAsync();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
}
{
progressBar1.Value = e.ProgressPercentage;
}
}
}