如何停止使用按钮for循环? [英] How to stop a for loop using a button?

查看:212
本文介绍了如何停止使用按钮for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个循环,我想停止使用一个按钮。
编辑为了更好的理解:

我不明白,而循环正在运行,你不能阻止一个按钮,因为它不会,只要是当前的UI运行工作。我真正要求的是创建一个线程或使用BGWorker停止这种最有效的方式。我已经看到了一些方法,但其中大部分都是针对Java,而不是C#。

我想这样做的是:

 私人无效start_Click(对象发件人,EventArgs的发送)
{    的for(int i = 0; I< NUMS;我++)
    {
        做一点事();
    }
}私人无效stop_Click(对象发件人,EventArgs的发送)
{    停止start_Click()
}


解决方案

您不能这样做。对于初学者来说,循环UI线程,这意味着你甚至不会在同步运行的能够的点击停止按钮

因此​​,你需要移动的操作循环到另一个线程,这意味着你可能不会使用循环的全部。你需要考虑如何在内部code的真正的需要被执行,然后根据你如何做处理,就可以实现停止按钮。

有一个非常简单的方法,这样做是只:

 新的Thread(()=>
{
   INT I = 0;
   而(停止&安培;!&安培; I< NUM)
   {
      做一点事();
      我++;
   }
 })。开始();

和设置停止停止处理循环。在更现实的情况下,您可以排队要处理的功能,然后停止通过类似的方法出列。不幸的是,它很难reccommend一个安装在不知道更多的细节。

根据您的code任何解决方案也将有目前的问题 DoSomething的()执行完成(这可能需要一段时间)。再次,没有更多的信息,很难说来固定,最好的办法那是什么。

I have a loop that I would like to stop using a button. Edited for better understanding:

I do realize that you cannot stop a button while a loop was running since it will not work as long as that current UI is running. What I'm really asking for is the most efficient way of creating a thread or using BGWorker to stop this. I have seen some methods, but most of them are for Java and not C#.

What I would like to do is:

private void start_Click(object sender, EventArgs e)
{

    for(int i = 0; i < nums; i++)
    {
        doSomething();
    }
}

private void stop_Click(object sender, EventArgs e)
{

    stops start_Click()
}

解决方案

You can't do that. For starters, the for loop is running synchronously on the UI thread, which means you won't even be able to click the "Stop" button.

Hence, you need to move the operations of the for loop onto another thread, which means you likely won't be using a for loop at all. You need to think about how the code inside actually needs to be executed, then based on how you are doing the processing, you can implement the "Stop" button.

A very simple way to do this would be to just:

new Thread(() =>
{
   int i = 0;
   while (!stop && i < num)
   {
      doSomething();
      i++;
   }
 }).Start();

And set stop to stop the processing loop. In a more realistic scenario, you could queue up functions that you want to process, then stop dequeuing via a similar method. Unfortunately, its hard to reccommend a setup without knowing more details.

Any solution based on your code will also have the problem of the current doSomething() completing execution (which could take a while). Again, without more info, its hard to say what the best approach to fixing that is.

这篇关于如何停止使用按钮for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆