2011-11-21 59 views
1

我有一個winform應用程序,它顯示了一些信息及時,每次加載數據時,我設置了7秒的延遲時間,像這樣:System.Threading.Thread.Sleep(7000),因此可以查看信息。我想要有一個按鈕,可以讓我無需等待即可跳到下一個信息。刪除延遲時間:System.Threading.Thread.Sleep使用c#(包括代碼)

我使用的邏輯如下:獲取信息,如果有的話,等待7秒,接下來的數據等等。所以,如果我按下按鈕,我想將時間設置爲0.

有什麼方法可以取消等待時間?

這裏是代碼:

ManualResetEvent wait_handle = new ManualResetEvent(true); 

{...}

private void TheLoop(object stateinfo) 
    { 
     bool hasInfo = true;    
     bool hasLines = GetLinesOnProduction(); 
     while (doLoop) 
     { 
      wait_handle.WaitOne(); 

      if (hasLines) 
      { 
       param1 = Lines[CurrentLine].line; 
       param2 = Lines[CurrentLine].WO; 

       //Here I query the DB for the CurrentLine Data      
       ShowLineInformation(CurrentLine); 
       ShowChartByHour(param1, param2, out hasInfo); 
       if (hasInfo) 
        System.Threading.Thread.Sleep(7000);           
       //Here I move to the next line 
       if (CurrentLine < Lines.Count - 1) 
        CurrentLine++; 
       else 
       { 

        CurrentLine = 0; //Start all over again 
        hasLines = GetLinesOnProduction(); 
       } 
      } 
      else 
      { 
       System.Threading.Thread.Sleep(40000); //(No Lines)Wait to query for lines again 
       hasLines = GetLinesOnProduction(); 
      } 
     } 
    } 

private void btnPauseResume_Click(object sender, EventArgs e) 
    { 
     if (btnPauseResume.Text == "Pause") 
     { 
      btnPauseResume.Text = "Resume"; 
      wait_handle.Reset(); 
     } 
     else 
     { 
      btnPauseResume.Text = "Pause"; 
      wait_handle.Set(); 
     } 
    } 
+3

請告訴我們你的代碼。你應該使用多個按鈕。 – SLaks

+0

'wait_handle.WaitOne();'只等待wait_handle爲Set()。您必須指定等待的毫秒數量,在這種情況下爲'WaitOne(7000)'。 – CodeCaster

+0

@CodeCaster,但我使用該WaitOne();暫停/恢復線程,我不希望在這一點上有任何等待時間。據我所知,我必須把它放在我想要做這些操作的地方。 – Somebody

回答

3

而不是執行Thread.Sleep,您可以使用等待事件,並簡單地將其設置爲取消等待。是這樣的:

var waiter = new AutoResetEvent(false); 
bool wasCanceled = waiter.WaitOne(7000); 
if(wasCanceled) 
    // Jump to next... 


// Cancel the wait from another thread 
waiter.Set() 
+0

謝謝,事情是,我也有一個暫停/恢復按鈕,這將影響其功能。 – Somebody

+0

嘿,我將暫停/簡歷與您的解決方案結合起來,並且都可以工作,非常感謝! – Somebody

2

而不是使用Thread.Sleep,將暫停在UI的所有活動,使用計時器來代替。使用計時器,當您的計時器回調待處理時,用戶界面仍然可以響應事件,並且當您單擊該按鈕時,可以取消計時器。

+0

感謝您的回覆,我還使用一個按鈕來暫停/恢復線程,就像@CodeCaster所說的那樣,會是您的解決方案出現問題嗎? – Somebody

+0

如果你需要暫停和恢復,你將不得不編寫自己的代碼來支持它。 '定時器'沒有內置的能力。 – Jacob

0

我會成立的延遲通過lock荷蘭國際集團的object然後上執行的Monitor.Wait具有7秒的延遲。然後,從表單中按下按鈕時,lockobject並執行Monitor.PulseAll

0

你可以使用一個ManualResetHandle

// Declare it as class member 
ManualResetHandle _manualResetHandle = new ManualResetHandle(); 

// Wait in your process for seven seconds, or until it is Set() 
_manualResetHandle.WaitOne(7000); 

// Set() it in your click event handler: 
_manualResetHandle.Set(); 
+0

感謝您的回覆,我用它來暫停/恢復主題,我不認爲這會消除等待時間。 – Somebody

+1

@你有沒有試過? – CodeCaster

+0

Yeap,它不起作用。 :( – Somebody