如何从不同的按钮停止循环 [英] How to stop for loop from different button
本文介绍了如何从不同的按钮停止循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个按钮
一个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 thefor
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屋!
查看全文