Getnet
Getnet

Reputation: 31

How to abort a while loop by clicking a button using C#

I have a function that displays numbers using a while loop but I want to stop execution of a while loop at random variable value using c# by clicking a button.

For Example:

private void FrqSent()
{
    int i = 1;
    while (i <= 5)       
    {  
        i = i + 1;
    }  
}

Upvotes: 2

Views: 2999

Answers (2)

Paul Weiland
Paul Weiland

Reputation: 737

Here is a quick example on how you can use a Backgroundworker to accomplish your task:

public partial class Form1 : Form
{
    private int i = 1;

    public Form1()
    {
        InitializeComponent();
    }

    private void FrqSent()
    {           
        while (i <= 500000000)
        {
            if (backgroundWorker1.CancellationPending)
            {
                break;
            }
            else
            {
                i = i + 1;
            }
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        backgroundWorker1.CancelAsync();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        FrqSent();
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        MessageBox.Show(i.ToString());
    }
}

Just create a new Windows-Forms Project and add a backgroundworker object aswell as 2 buttons. You have to set the DoWork, RunWorkerCompleted and Click events manually.

Edit: Do not forget to set the BackgroundWorker`s WorkerSupportsCancellation property to true.

Upvotes: 6

Ali
Ali

Reputation: 2160

not very elegant but simple

public partial class Form1 : Form
{
    private bool _stop;

    public Form1()
    {
        InitializeComponent();
    }

    private void buttonStart_Click(object sender, EventArgs e)
    {
        _stop = false;
        FrqSent();
    }

    private void buttonStop_Click(object sender, EventArgs e)
    {
        _stop = true;
    }

    private void FrqSent()
    {
        int i = 1;
        while (i <= 5000000 && !_stop)
        {
            i = i + 1;
            Application.DoEvents();
        }
    }

}

Upvotes: 1

Related Questions