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

时间:2016-04-14 12:45:21

标签: c# loops while-loop break

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

例如:

agenda.image = UIImagePNGRepresentation(image)

2 个答案:

答案 0 :(得分:4)

以下是一个关于如何使用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窗体项目并添加一个backgroundworker对象以及2个按钮。您必须手动设置DoWork,RunWorkerCompleted和Click事件。

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

答案 1 :(得分:0)

不是很优雅而是简单

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

}