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

Get*_*net 2 c# loops break while-loop

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;
    }  
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*and 5

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

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.