如何通过使用 C# 单击按钮来中止 while 循环

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

我有一个使用 while 循环显示数字的函数,但我想通过单击按钮停止使用 c# 以随机变量值执行 while 循环。

例如:

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

这里是一个关于如何使用 Backgroundworker 完成任务的简单示例:

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());
    }
}

只需创建一个新的 Windows-Forms 项目并添加一个 backgroundworker 对象以及 2 个按钮。您必须手动设置 DoWork、RunWorkerCompleted 和 Click 事件。

编辑:不要忘记将 BackgroundWorker 的 WorkerSupportsCancellation 属性 设置为 true。

不是很优雅但很简单

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();
        }
    }

}