如何从不同的按钮停止循环 [英] How to stop for loop from different button

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

问题描述





我有两个按钮

一个asp.net控制按钮启动和其他html按钮停止。



在开始按钮中我为循环代码编写了

Hi,

I have two button
one asp.net control button start and other html button stop .

in start button i have written for loop code as

protected void Button2_Click(object sender, EventArgs e)
   {

for(int i=0;i<=50000;i++)
{
 //dosomething
}

}





我想要的是当用户点击停止按钮for循环时应该存在。



what i want is when user click on stop button for loop should exist.

推荐答案

在你提出的场景中(两个GUI线程中的操作)你不能这样做。

为了正确地做到这一点,你应该移动 for 循环工人线程。

请参阅Windows窗体中的多线程控件 [ ^ ]。
In the scenario you proposed (both the operation in the GUI thread) you cannot do that.
In order to properly do that, you should move the for loop in a worker thread.
See, for instance "Multithreading in Windows Forms Controls"[^].


看我在asp.net中做了一个解决方案

代码如下:



See I did a solution in asp.net
Code are following below

Thread thLoop = null;
    static string value = "";
    static bool isStopRequired = false;
    protected void Button1_Click(object sender, EventArgs e)
    {
        isStopRequired = false;
        value = "";
        thLoop = new Thread(new ThreadStart(GetLoop));
        thLoop.Start();
    }
    void GetLoop()
    {
        for (int i = 0; i <= 50000; i++)
        {
            value += "  " + i.ToString();
            if (isStopRequired) break;
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        isStopRequired = true;
        if (thLoop != null) thLoop.Abort();
        Response.Write(value);
    }


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

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