2015-12-25 106 views
0

我告訴Timer在構造函數中啓動。它開始,但是當它到達Timer.Elapsed事件時,它只運行方法中的第一個if語句。我已檢查isWatching是否屬實,它是,但它仍然完全跳過它。它甚至沒有達到if(isWatching)系列。C#定時器跳過代碼

代碼:

MainWindow.xaml.cs

public partial class MainWindow : Window 
{ 
    public SessionManager SM { get; private set; } 

    public MainWindow() 
    { 
     SM = new SessionManager(); 
     SM.NewDayEvent += SplitSession; 
     ///code 
    } 
} 

SessionManager.cs(有些變量已經從這篇文章中省略):

public class SessionManager : INotifyPropertyChanged 
{ 
    public delegate void NewDayEventHandler(object sender, EventArgs ea); 
    public event NewDayEventHandler NewDayEvent; 

    private bool _isWatching; 
    private Timer _timer; 
    private bool isWatching 
    { 
     get 
     { 
      return _isWatching; 
     } 
     set 
     { 
      _isWatching = value; 
      if (!_isWatching) 
      { 
       _clockWatch.Stop(); 
      } 
      else 
      { 
       _clockWatch.Start(); 
      } 
     } 
    } 
    #endregion 


    public SessionManager() 
    { 
     _clockWatch = new Stopwatch(); 
     _timer = new Timer(1000); 
     _timer.Elapsed += timerElapsed;//focus on this here 

     _isWatching = false; 
     current_time = new DateTime(); 
     CurrentTime = DateTime.Now; 
     _timer.Start(); 
    } 

    public void timerElapsed(object sender, ElapsedEventArgs e) 
    { 
     CurrentTime = DateTime.Now; 
     if (CurrentTime.TimeOfDay == TimeSpan.Parse("9:32 AM") && NewDayEvent != null) 
     { 
      NewDayEvent(this, new EventArgs()); 
     } 
     if (isWatching) 
     { 
      if (CurrentSession != null) 
      { 
       //update the timespent variable of the current timeEntry 
       if (CurrentSession.currentTimeEntry != null) 
       { 
        CurrentSession.currentTimeEntry.TimeSpent = _clockWatch.Elapsed; 
        calculateTotalTime(); 

        CalculateFilteredTimeSpent(); 
       } 
      } 
     } 
    } 
} 
+0

順便說一下,我在Debug中運行。 –

+1

CurrentSession值如何?它是否爲空? – Shyju

+0

@Shyju:我已經檢查過isWatching是否真的,它是,但它仍然完全跳過它。它甚至沒有達到if(isWatching)行。如果它沒有達到這一線,爲什麼會更深入? –

回答

3

你AREN在撥打TimeSpan.Parse()時,請勿使用正確的格式。正確的方式做你正在嘗試是什麼:

TimeSpan.Parse("9:32") 

您當前的代碼片段拋出一個System.FormatException

A first chance exception of type 'System.FormatException' occurred in mscorlib.dll 

但是你正在努力實現的目標,每天一次觸發動作的在特定的時間,上述方法可能不是最好的,因爲它成功的可能性非常小。計時器將每1000毫秒運行一次,然後返回包含毫秒的當前時間。所以計時器已過去的事件可以在9:32.0001被調用,並且可能永遠不會通過該條件。一個更好的選擇可能是:

if (CurrentTime.TimeOfDay >= TimeSpan.Parse("9:32") && NewDayEvent != null) 

這將觸發一次以上時間已經過去之後,所以你可以添加哪些跟蹤被處理那一天的最後一個事件的一個標誌。

或者你也可以看看ScheduleAction在.NET 4.5或部分解決方案here的。

+0

但我需要TimeSpan的AM/PM部分最多。有什麼方法可以讓我仍然有嗎?此外,爲什麼我在運行代碼時沒有拋出錯誤?它從來沒有對我說過任何話。 –

+0

@SageKelly'TimeSpan'中的小時數從0到23,因此'9'是_ante meridiem_。 – HABO

+0

查看上面的鏈接。該論點以24小時制接受時間。如果您要輸入9:32 PM,則可以簡單鍵入21:32。對於AM來說,它很簡單。 錯誤沒有被拋出,因爲異常發生在與你的主線程分開的timer _elapsed線程上。嘗試在MainWindow.cs文件中執行相同的操作,你會看到異常。 – degant