Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping an thread application in C# Windows Application?

Tags:

c#

windows

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.

like image 797
Dany Avatar asked Mar 19 '26 01:03

Dany


2 Answers

Take a look at Background Worker its very easy to do threading :)

like image 133
John Avatar answered Mar 20 '26 15:03

John


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();      
}
like image 24
Pranay Rana Avatar answered Mar 20 '26 13:03

Pranay Rana