繁体   English   中英

在满足条件之前如何入睡

[英]How to sleep until condition is met

启动应用程序时,我需要检查我的一项服务是否正在运行。 如果服务未运行,则必须允许用户启动服务,然后继续执行。 如果用户选择不启动服务,那么我必须退出应用程序。 每隔10秒钟我必须弹出一条消息以启动服务,在此期间程序不应继续执行。下面是我编写的代码。 但是我不喜欢for循环中的条件i <10(如果用户需要更多时间来启动服务。我也不希望从Config文件中获取此值)。

没有写条件就可以实现这一目标吗? 我们也可以使用计时器来实现吗? 请举同样的例子。

for (int i = 0; i < 10; i++) {
    if (!CheckifServiceStarted()) {
        DialogResult dlgResult = MessageBox.Show("Service is not Started.Please  start Service to continue", "Start Service", MessageBoxButtons.YesNo);

        if (dlgResult == DialogResult.Yes) {
            Thread.Sleep(10000);
        }
        else {
            System.Environment.Exit(0);
        }
    }
}

只需一点点休息就可以检查状况

for (int i = 0; i < 10; i++) {
    if (!CheckifServiceStarted()) {
        DialogResult dlgResult = MessageBox.Show("Service is not Started.Please  start Service to continue", "Start Service", MessageBoxButtons.YesNo);

    if (dlgResult == DialogResult.Yes) {
        for (int j = 0; j < 10; j++)
            if (!CheckifServiceStarted())
                Thread.Sleep(1000);
    }
    else {
        System.Environment.Exit(0);
    }
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM