[英]How to sleep until condition is met
When I start my application I need to check if one of my service is running. 启动应用程序时,我需要检查我的一项服务是否正在运行。 If service is not running then I have to allow the user to start the service and then execution continues.
如果服务未运行,则必须允许用户启动服务,然后继续执行。 If User chooses not to start the service then I have to Exit the Application.
如果用户选择不启动服务,那么我必须退出应用程序。 For every 10 sec I have to pop up the message to start the service,during this time program execution should not continue.Below is the code I have written.
每隔10秒钟我必须弹出一条消息以启动服务,在此期间程序不应继续执行。下面是我编写的代码。 But I did not like the condition i<10 (what if user takes more time to start the service.Also I dont like to take this value from Config file) in the for loop.
但是我不喜欢for循环中的条件i <10(如果用户需要更多时间来启动服务。我也不希望从Config文件中获取此值)。
Is there any way to achieve this without writing the condition? 没有写条件就可以实现这一目标吗? Can we achieve this using Timers also?
我们也可以使用计时器来实现吗? Please give examples for same.
请举同样的例子。
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);
}
}
}
Just break the sleep in small increment and check condition 只需一点点休息就可以检查状况
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.