2012-02-10 30 views
1

我的程序中有一個事件,其中值爲tantheta的事件在後續事件觸發中不斷變化。在函數內計數3秒

問題是我必須檢查tantheta這個值是否在0.6 to 1.5的某個範圍內持續3秒的時間。

我用計時器嘗試過一些東西,但沒有成功。有什麼建議麼?

EDIT--

DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer(); 
//This event is fired automatically 32 times per second. 
private void SomeEvemt(object sender, RoutedEventArgs e) 
{ 
tantheta = ; tantheta gets a new value here through some calculation 

timer.Tick += new EventHandler(timer_Tick); 
timer.Interval = new TimeSpan(0, 0, 5); 
timer.Start(); 
//if condition to check if tantheta is within range and do something 

} 

void timer_Tick(object sender, EventArgs e) 
     { 
      DispatcherTimer thisTimer = (DispatcherTimer)sender; 
      textBox1.Text = thisTimer.Interval.ToString(); 
      thisTimer.Stop(); 
      return; 
     } 

我要檢查是否tantheta值保持0.6內1.三秒鐘。我雖然計時器會是一個好方法,因爲它會阻止我的應用程序在所有這些計算過程中凍結,因爲它會轉到單獨的線程。 : -/

+3

什麼,特別是,你試試? – 2012-02-10 05:23:33

+1

爲什麼計時器不工作,你可以顯示你的代碼 – 2012-02-10 05:24:41

+0

編輯帖子 – Cipher 2012-02-10 05:35:05

回答

2

一個計時器是無用的,因爲你會輪詢太多次,錯過了改變/改變回來。

您將不得不封裝變量的設置。 這樣你可以響應變量的變化。

class A 
{ 
    private double _tantheta; // add public getter 
    private bool _checkBoundaries; // add public getter/setter 
    public event EventHandler TanThetaWentOutOfBounds; 
    public void SetTantheta(double newValue) 
    { 
     if(_checkBoundaries && 
      (newValue < 0.6 || newValue > 1.5)) 
     { 
      var t = TanThetaWentOutOfBounds; 
      if(t != null) 
      { 
       t(this, EventArgs.Empty); 
      } 
     } 
     else 
     { 
      _tantheta = newValue; 
     } 
    } 

現在,所有你需要做的就是訂閱這個類的TanThetaWentOutOfBounds事件和CheckBoundaries設置爲true或false。

請注意,此代碼不會修復任何多線程問題,因此您可能必須添加一些鎖,具體取決於您對該類的使用情況。

有處理3個秒鐘的時間段雙向的:

  1. 在TanThetaWentOutOfBounds處理器(即註冊了該事件的一些其他類)保留的上次更新的時間軌跡,只有採取行動時,該事件在測量開始後3秒內提高。這樣實施期限的責任就交給了消費者。

  2. 只有在上次事件發生後少於3秒的時間內,您纔可以決定提升事件。通過這種方式,您可以將所有消費者限制在您在提升者中實施的時期。請注意,我使用DateTime.Now來獲得時間,這不像Stopwatch類那樣精確。

代碼:

class A 
{ 
    private double _tantheta; // add public getter 
    private DateTime _lastRaise = DateTime.MinValue; 
    private bool _checkBoundaries; // add public getter/setter 
    public event EventHandler TanThetaWentOutOfBounds; 
    public void SetTantheta(double newValue) 
    { 
     if(_checkBoundaries && 
      (newValue < 0.6 || newValue > 1.5)) 
     { 
      var t = TanThetaWentOutOfBounds; 
      if(t != null) 
      { 
       var now = DateTime.Now; 
       if((now - _lastRaise).TotalSeconds < 3) 
       { 
        t(this, EventArgs.Empty); 
        _lastRaise = now; 
       } 
      } 
     } 
     else 
     { 
      _tantheta = newValue; 
     } 
    } 
+0

我想你錯過了3秒計數聲明在這裏。我必須在三秒內通過並且tantheta值保持在邊界內才能起火。這可以包括在這裏嗎? – Cipher 2012-03-23 06:22:01

+0

我添加到我的答案。 – 2012-03-23 08:37:12

0

我的猜測是你想要一個函數以外的變量跟蹤上次調用該函數。這樣您就可以檢查自上次調用以來是否已經過了3秒。不需要Timer對象。

+0

編輯帖子 – Cipher 2012-02-10 05:36:03