简体   繁体   中英

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. 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.

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);
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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