It shows how to implement threading using Backgroundworker control in C#.NET
Keywords: Backgroundworker, DoWork, thread, threading, C#.NET, C Sharp.NET
Do the following:
1) Add two Button controls, a ListBox and a ProgressBar control to Form
2) Add a BackgroundWorker control to Form
3) Set its WorkerReportsProgress and WorkerSupportsCancellation properties to True
4) Add the following the form’s code:
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;
namespace testc
{
public partial class Form1 : Form
{
private int mMin;
private int mMax;
private List<int> mResults = new List<int>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnstart_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
mMin = 1;
mMax = 10000;
backgroundWorker1.RunWorkerAsync();
}
private void btnstop_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
private void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
foreach (int item in mResults)
{
listBox1.Items.Add(item);
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
mResults.Clear();
for (int count = mMin; count <= mMax; count += 2)
{
bool isPrime = true;
for (int x = 1; x <= Convert.ToInt32(count / 2); x++)
{
for (int y = 1; y <= x; y++)
{
if (x + y == count)
{
//the number is not prime
isPrime = false;
break; // TODO: might not be correct. Was : Exit For
}
}
//short-circuit the check
if (!isPrime)
break; // TODO: might not be correct. Was : Exit For
}
if (isPrime)
{
mResults.Add(count);
}
this.backgroundWorker1.ReportProgress(Convert.ToInt32((count - mMin)
/ (mMax - mMin) * 100));
if (this.backgroundWorker1.CancellationPending)
{
return;
}
}
}
}
}
No comments:
Post a Comment