[英]Wait for maximum 5 seconds
我正在嘗試實現一些等待布爾值變為真的東西。 如果5秒鍾后布爾值仍然不是true,那么我將執行錯誤消息代碼
這就是我現在正在做的。 但是這種方法在所有情況下都只等待5秒鍾,這很浪費時間。 我該如何做這樣的事情,一旦變量變為true,它就會立即執行?
Thread.Sleep(5000);
if (imageDisplayed == true) {
//success
}
else {
//failed
}
最好為此使用ManualResetEvent 。
// Somewhere instantiate this as an accessible variable to both
// display logic and waiting logic.
ManualResetEvent resetEvent = new ManualResetEvent(false);
// In your thread where you want to wait for max 5 secs
if(resetEvent.WaitOne(5000)) { // this will wait for max 5 secs before continuing.
// do your thing
} else {
// run your else logic.
}
// in your thread where you set a boolean to true
public void DisplayImage() {
// display image
display();
// Notify the threads waiting for this to happen
resetEvent.Set(); // This will release the wait/lock above, even when waiting.
}
經驗法則。 最好不要在生產代碼中使用睡眠,除非您確實有一個非常非常好的理由。
將您的睡眠分解為“小睡”。 ;)
for (int n = 0; n < 50; n++)
{
Thread.Sleep(100);
if (imageDisplayed)
{
// success
break;
}
}
//failed
並非立即完成,但最大延遲為100毫秒。
您可以將timeout變量設置為要停止等待的時間,並在while循環中將其與等待的檢查一起使用。 在下面的示例中,兩次檢查之間我們只睡眠十分之一秒,但是您可以根據需要調整睡眠時間(或刪除睡眠時間):
var timeout = DateTime.Now.AddSeconds(5);
while (!imageDisplayed && DateTime.Now < timeout)
{
Thread.Sleep(100);
}
// Here, either the imageDisplayed bool has been set to true, or we've waited 5 seconds
使用while循環並逐步檢查您的狀況
var waitedSoFar = 0;
var imageDisplayed = CheckIfImageIsDisplayed(); //this function is where you check the condition
while(waitedSoFar < 5000)
{
imageDisplayed = CheckIfImageIsDisplayed();
if(imageDisplayed)
{
//success here
break;
}
waitedSoFar += 100;
Thread.Sleep(100);
}
if(!imageDisplayed)
{
//failed, do something here about that.
}
聽起來像您想使用System.Timers.Timer類。
設置布爾變量以將其設置為true時執行一個函數
System.Timers.Timer t;
private bool val;
public bool Val {
get { return val; }
set
{
if (value == true)
// run function here
val = value;
}
}
然后設置您的計時器間隔為每5秒。
public Main()
{
InitializeComponent();
t = new System.Timers.Timer(5000);
t.Elapsed += T_Elapsed;
}
private void T_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
throw new Exception();
}
要啟動計時器,只需使用t.Start()
和t.Reset()
重置計時器
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.