【发布时间】:2014-04-14 08:06:11
【问题描述】:
有没有办法做任何循环并打破它,直到另一个按钮 WinForms 按下了吗?
do
{
//Action
} while ("Button Stop is pressed");
【问题讨论】:
有没有办法做任何循环并打破它,直到另一个按钮 WinForms 按下了吗?
do
{
//Action
} while ("Button Stop is pressed");
【问题讨论】:
在不阻塞 gui 的情况下执行此操作的最佳方法是使用线程,例如:
Thread t = new Thread (delegate() {
while(true) {
What you want to happen inside the loop in here;
Thread.Sleep(500); // this is useful for keeping the headroom of the CPU
}
});
以这种方式启动线程:
t.Start();
当按下停止按钮时,以这种方式中止线程:
t.Abort();
这使 gui 保持活力。
【讨论】:
Thread.Abort,这是终止线程的可怕方式:stackoverflow.com/questions/421389/…
有两种可能的情况:
1-您正在主线程中运行该循环,那么答案是否定的,如果您阻塞主线程事件将不会触发并且无法捕获按钮点击。
2-您正在工作线程中运行该循环,在这种情况下,您可以在设置为 true 的函数之外创建一个布尔值,在循环中检查此布尔值并在按钮的单击事件中将其设置为 false。
【讨论】: