using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace SampleBackgroundWorker
{
public partial class Form1 : Form
{
int COUNTER_DONE;
BackgroundWorker bw =
new BackgroundWorker
();
byte WorkingCounter = 0;
public Form1()
{
InitializeComponent();
COUNTER_DONE = int.Parse(textBox1.Text);
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
bw.
DoWork +=
new DoWorkEventHandler
(bw_DoWork
);
bw.
ProgressChanged +=
new ProgressChangedEventHandler
(bw_ProgressChanged
);
bw.
RunWorkerCompleted +=
new RunWorkerCompletedEventHandler
(bw_RunWorkerCompleted
);
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
button3.Enabled = false;
button2.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
button2.Enabled = true;
button3.Enabled = true;
button3.Text = "Pause";
bw.RunWorkerAsync((object)false);
}
private void button2_Click(object sender, EventArgs e)
{
if (bw.IsBusy)
{
button2.Enabled = false;
bw.CancelAsync();
}
}
private void button3_Click(object sender, EventArgs e)
{
if (bw.IsBusy)
{
button2.Enabled = false;
button3.Text = "Resume";
bw.CancelAsync();
}
else
{
button1.Enabled = false;
button3.Text = "Pause";
bw.RunWorkerAsync((object)true);
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
bool resume = (bool)e.Argument;
if (!resume)
{
WorkingCounter = 0;
}
while (WorkingCounter < COUNTER_DONE)
{
Random rnd =
new Random
();
if (WorkingCounter > (WorkingCounter += 10))
{
throw new Exception
(string.
Format("Dépassement du type du compteur : {0} pour {1}.",
(byte)(WorkingCounter -
10) +
10,
byte.
MaxValue));
}
int Percent = (int)WorkingCounter * 100 / COUNTER_DONE;
bw.ReportProgress(Percent, (object)false);
System.Threading.Thread.Sleep(250);
if (bw.CancellationPending)
{
e.Cancel = true;
bw.ReportProgress(Percent, (object)true);
System.Threading.Thread.Sleep(500);
break;
}
}
e.Result = (object)WorkingCounter;
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
if ((bool)e.UserState)
{
label1.Text = "Le worker est en cours d'arrêt...";
}
else
{
label1.Text = string.Format("Le worker fonctionne normalement... ({0}%)", e.ProgressPercentage);
}
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
label1.Text = string.Format("Le worker s'est terminé avec une erreur :\n{0}.", e.Error.Message);
}
else
{
if (e.Cancelled)
{
label1.Text = "Le worker s'est arrêté à la demande de l'utilisateur.";
button3.Enabled = false;
}
else
{
label1.Text = string.Format("Le worker a fini de compter jusqu'à {0}.", e.Result);
button3.Enabled = true;
}
}
button1.Enabled = true;
button2.Enabled = false;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
COUNTER_DONE = int.Parse(textBox1.Text);
}
}
}