【问题标题】:Any cycle, until another button is pressed C#任何循环,直到按下另一个按钮 C#
【发布时间】:2014-04-14 08:06:11
【问题描述】:

有没有办法做任何循环并打破它,直到另一个按钮 WinForms 按下了吗?

do
        {
            //Action
        } while ("Button Stop is pressed");

【问题讨论】:

标签: c# cycle


【解决方案1】:

在不阻塞 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 保持活力。

【讨论】:

【解决方案2】:

有两种可能的情况:

1-您正在主线程中运行该循环,那么答案是否定的,如果您阻塞主线程事件将不会触发并且无法捕获按钮点击。

2-您正在工作线程中运行该循环,在这种情况下,您可以在设置为 true 的函数之外创建一个布尔值,在循环中检查此布尔值并在按钮的单击事件中将其设置为 false。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 2021-10-08
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    相关资源
    最近更新 更多