简体   繁体   English

如何使用按钮停止长时间运行的循环

[英]How to stop long running loop using button

I have c# application which having 2 buttons.我有具有 2 个按钮的 c# 应用程序。 First having for loop which is run 10k times.首先有运行 10k 次的 for 循环。 and each loop code execution take 1 second to finish.每个循环代码执行需要 1 秒才能完成。

    for(int i=0;i<10000;i++){
      //My running code take 1 sec for each loop
    }

some time i want to stop this loop/ execution on click on another button "Stop", but its not working.有时我想通过单击另一个按钮“停止”来停止此循环/执行,但它不起作用。 Please suggest me what solution.请建议我什么解决方案。

It's not good practice to run long running operations in UI Thread (thread where all UI events are handled - such as button click).UI Thread (处理所有 UI 事件的线程 - 例如按钮单击)中运行长时间运行的操作不是一个好习惯。 You should run your loop in another that.你应该在另一个循环中运行你的循环。

You can use Task Parallel Library (TPL) :您可以使用Task Parallel Library (TPL)

    private bool stopIt = false;

    private void Form1_Load(object sender, EventArgs e)
    {
        Task task = Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 1000000000; i++)
                {
                    if (!stopIt)
                    {
                        Console.WriteLine("Here is " + i);
                    }
                    else
                    {
                        break;
                    }
                }
            });
    }

    private void button1_Click(object sender, EventArgs e)
    {
        stopIt = true;
    }

The simplest solution (not best) is to add Application.DoEvents() into the loop to process button events:最简单的解决方案(不是最好的)是将Application.DoEvents()添加到循环中以处理按钮事件:

private bool cancel;

public void loop()
{
    for(int i=0;i<10000;i++){
      //My running code take 1 sec for each loop
       Application.DoEvents();
       if (cancel)
          break;
    }
}

public void cancelButton_Click(object sender, EventArgs e)
{
      cancel=true;
}

Much better and still simple solution is to employ async Task (the rest of the code stays the same minus Application.DoEvents() call):更好且仍然简单的解决方案是使用异步Task (其余代码保持不变,减去Application.DoEvents()调用):

private void loopButton_Click(object sender, EventArgs e)
{
    new Task(loop).Start();
}

Beware that you should use this.Invoke(new Action(() => { <your code> } ));请注意,您应该使用this.Invoke(new Action(() => { <your code> } )); to access UI controls from the loop in this case.在这种情况下从循环访问 UI 控件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM