I am making a windows application in c# in which on button click i have written some code as
public void btnStart_Click(object sender, EventArgs e)
{
while(true)
{
//some processing
}
}
when i starts application it running continuously. But on other button i want to stop that application. But i am not getting how to do it?Please help me.
Take a look at Background Worker its very easy to do threading :)
You can make user of timer of C# here is one example of the stopwatch using timer : Creating a simple Stopwatch/Timer application with C# / Windows Forms
here is one example : Check full answer and code at : C# start /Stop Button
example with using BackGroundWorker (its a bit changed version of AmaL`s code snipet):
BackgroundWorker bgw;
Stopwatch watch;
public Form1()
{
InitializeComponent();
label1.Text = "";
watch = new Stopwatch();
bgw = new BackgroundWorker();
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
bgw.WorkerReportsProgress = true;
bgw.WorkerSupportsCancellation = true;
}
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
bgw.ReportProgress(0);
System.Threading.Thread.Sleep(100);
if (!watch.IsRunning)
break;
}
}
private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
TimeSpan ts = watch.Elapsed;
label1.Text = String.Format("{0:00}:{1:00}:{2:00}", ts.Minutes, ts.Seconds, ts.Milliseconds);
}
private void button1_Click(object sender, EventArgs e)
{
watch.Start();
bgw.RunWorkerAsync();
}
private void button2_Click(object sender, EventArgs e)
{
watch.Stop();
watch.Reset();
bgw.CancelAsync();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With