I have used the last program above but whilst if I make a public integer Q and run it in a long for loop in the startloading method it counts up, which is just fine, and can be stopped by the other button. But I wanted to see the count as it runs by putting a textbox with an update() inside startloading, but it says I have a "cross threading exception" if I do this. So I added another public integer CQ (this stands for "cancel Q") and the it is set to zero and also set to zero when the start button is pressed. But when the stop button is pressed CQ is set to one. An if(Q==1){Break;} is inserted inside the for loop inside the startloading method, and this works, it exits the loop when the stop button is pressed and if the loop is not finished shows the count up to the time the button was pressed, a bit like a stopwatch. But as for the remaining problem of actually displaying the count "live" I simply set a timer at a high tick rate and put this in the timer (see below) textBox1.Update; textBox1.Text=Q.toString(); But is their a more conventional way of achieving this? See code below
using System.ComponentModel;
namespace startstop2 { public partial class Form1 : Form { public int Q = 0; public int CQ = 0;
private BackgroundWorker bw = new BackgroundWorker();
public Form1()
{
InitializeComponent();
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)//start button
{
CQ = 0;
if (!bw.IsBusy)
{
bw.RunWorkerAsync();
}
}
private void button2_Click(object sender, EventArgs e)//stop button
{
CQ = 1;
if (bw.WorkerSupportsCancellation)
{
bw.CancelAsync();
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
if (worker.CancellationPending)
{
e.Cancel = true;
return;
}
StartLoading(); //Some Method which performing I want to stop at any time
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
//"Canceled!";
}
else if (e.Error != null)
{
//"Error: " + e.Error.Message);
}
else
{
//"Done!";
}
}
private void StartLoading()
{
for (int i=0;i<1000000000;i++)
{
if (CQ == 1) { break; }
Q++;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
textBox1.Update();
textBox1.Text = Q.ToString();
}
}
}