2017-06-15 104 views
0

我想實現一些等待布爾值爲true的東西。如果5秒後布爾值仍然不正確,那麼我將執行錯誤消息代碼等待最多5秒

這就是我現在要做的。但是這種方法只等待5秒鐘,這是浪費時間。我該如何做這樣的事情,一旦變量變爲true,就會執行這樣的事情?

Thread.Sleep(5000); 
if (imageDisplayed == true) { 
    //success 
} 
else { 
    //failed 
} 
+0

你應該做的是一個while循環,很快,因爲它擊中的時候,做了好事。 – TGarrett

+1

你應該*做的是改變實際上正在做的工作,比設置布爾值來指示何時完成,比如調用回調,返回一個指示何時完成的「Task」,發射事件等 – Servy

回答

3

爲此更好使用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. 
} 

經驗法則。最好不要在你的生產代碼中使用睡眠,除非你有真正的,真的很好的理由這樣做。

+0

謝謝,但你沒有忘記重置?我可以用'AutoResetEvent'做到這一點嗎? – user1984300

+0

您可以在設置後通過調用resetEvent.reset進行重設。使用AutoResetEvent時,您無法控制它的設置,因此對於您的情況不是很好。 – bastijn

0

把你的睡眠分解成「小睡」。 ;)

for (int n = 0; n < 50; n++) 
{ 
    Thread.Sleep(100); 
    if (imageDisplayed) 
    { 
     // success 
     break; 
    } 
} 
//failed 

不是很直接,但最大延遲爲100毫秒。

0

您可以將超時變量設置爲您想停止等待的時間,並將其與您正在等待的檢查一起用作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 
0

使用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. 
} 
-2

聽起來像你想要使用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()復位定時器

+0

應該'val'是'imageDisplayed',就像例子中那樣? –

+0

是的,這是正確的,我只是在解釋理論 – AviatorBlue