当我启动我的应用程序时,我需要检查我的某个服务是否正在运行。如果服务没有运行,那么我必须允许用户启动服务然后继续执行。如果用户选择不启动服务,那么我必须退出应用程序。每10秒我必须弹出消息来启动服务,在此期间程序执行不应该继续。下面是我编写的代码。但是我不喜欢条件i< 10(如果用户需要更多时间来启动服务,我也不喜欢从Config文件中获取此值)。
有没有办法在没有写条件的情况下实现这一目标?我们可以使用Timers实现这一目标吗?请举例说明。
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);
}
}
}
答案 0 :(得分: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);
}
}
}