簡體   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